Copy link to clipboard
Copied
I need to create a search feature.
There will be a textfield where the user will input a word or words.
Then I need to check if the are any reference in the array of names.
namesArray ["ocean in the sky", "cean on sky", "cean is white"];
keywordsArray ["cean", "sky"];
matchCounter = 0;
If I input the word "cean" I dont want in my results "ocean in the sky", only "cean is sky".
I have the following code:
for (var j:int = 0; j < namesArray.length; ++j)
{
var tempStr:String = namesArray
; for (var k:int = 0; k < keywordsArray.length; ++k)
{
if (tempStr.indexOf(arrayKeywords
) != -1) {
matchCounter++;
}
}
if(lengthKeywords == matchCounter)
{
trace("yeahhh... there's a match!!");
}
matchCounter = 0;
}
Is there a better way? How can I do this?
There are few things but the main problem is that "new RegExp()" needs double escapes ("\\")
......
var namesArray:Array = ["ocean in the sky", "cean on sky", "cean is white"];
var keywordsArray:Array = ["cean", "sky"];
for (var j:int = 0; j < namesArray.length; j++){
var matchCounter:uint = 0;
var tempStr:String = namesArray;
for (var k:int = 0; k < keywordsArray.length; k++){
Copy link to clipboard
Copied
indexOf() is no use for this if you want "ocean" to fail the test against "cean":
trace(("cean on the sky").indexOf("cean") > -1);
// true
trace(("ocean in the sky").indexOf("cean") > -1);
// true (<- you want this to be false)
RegExp is the answer
trace(("cean on sky").search(/(\s+|^)cean(\s+|$)/) > -1);
// true
trace(("ocean in the sky").search(/(\s+|^)cean(\s+|$)/) > -1);
// false
Copy link to clipboard
Copied
for (var j:int = 0; j < namesArray.length; ++j)
{
var tempStr:String = namesArray
; for (var k:int = 0; k < keywordsArray.length; ++k)
{
var strExp:String = '/(\s+|^)' + keywordsArray
+ '(\s+|$)/'; var regExp:RegExp = new RegExp(strExp);
if (tempStr.search(regExp) > -1)
{
matchCounter++;
}
}
if(keywordsArray.length == matchCounter)
{
trace("yeahhh... there's a match!!");
}
matchCounter = 0;
}
Much appreciated for your reply...
I tried something like this. But Its not working...
What I'm doing wrong?
Copy link to clipboard
Copied
There are few things but the main problem is that "new RegExp()" needs double escapes ("\\")
...
var namesArray:Array = ["ocean in the sky", "cean on sky", "cean is white"];
var keywordsArray:Array = ["cean", "sky"];
for (var j:int = 0; j < namesArray.length; j++){
var matchCounter:uint = 0;
var tempStr:String = namesArray;
for (var k:int = 0; k < keywordsArray.length; k++){
var regExp:RegExp = new RegExp("(\\s+|^)" + keywordsArray+ "(\\s+|$)");
if (tempStr.search(regExp) > -1){
matchCounter++;
}
}
if(keywordsArray.length == matchCounter){
trace("\"" + namesArray+ "\" matched all the keywords");
}
}...
Traces:
"cean on sky" matched all the keywords
Copy link to clipboard
Copied
hehehe you are the man!! It works!
I need to learn regular expression sintax as soon as possible...
Thank you, you helped a lot