0

How can I find array items in a text string?

I don't know the array and I don't know the text. But when an array item is contained in the text then party!

var arrayString = 'apple | ape | soap',
    text = "This a nice apple tree.";

var array = arrayString.split(" | ");

var matchedArrayItem = "..."; // please help on this

if(matchedArrayItem) {
    $("body").append('The text contains the array item "'+ matchedArrayItem +'".');
}

Test: http://jsfiddle.net/9RxvM/

2
  • regex should match something like /\b(apple|ape|tree)\b/ - you do not need jQuery here at all Commented Jan 12, 2014 at 14:10
  • stackoverflow.com/questions/1789945/… Commented Jan 12, 2014 at 14:12

2 Answers 2

1

Use JavaScript search(str).

var matchedArrayItem = "";
for(var i=0;i<array.length;i++){
    if(text.search(array[i])!=-1){
         matchedArrayItem = array[i];
         break;
    }
}

if(matchedArrayItem!="") {
    $("body").append('The text contains the array item "'+ matchedArrayItem +'".');
}

Note that this will get the first matched item in the array. To check if there is a matched item, just check if matchedArrayItem!="";

Sign up to request clarification or add additional context in comments.

1 Comment

How could I run this for multiple matches and replace the text output and array string? jsfiddle.net/9RxvM/4
1

One way with Regex:

var arrayString = 'apple|ape|soap',
  text = "This a nice apple tree.";

var matchedArrayItem = text.match(new RegExp("\\b(" + arrayString + ")\\b"));

if(matchedArrayItem) {
    $("body").append('The text contains the array item "'+ matchedArrayItem[0] +'".');
}

$("body").append("<br><br>" + arrayString + "<br>" + text);

Note: I removed the spaces from the array string to make it the correct format

Note2: match() returns an array of matches, so I take the first ([0]) result.

http://jsfiddle.net/9RxvM/2/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.