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/

Martin
  • 2,007
  • 6
  • 28
  • 44

2 Answers2

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!="";

Samleo
  • 605
  • 5
  • 16
  • How could I run this for multiple matches and replace the text output and array string? http://jsfiddle.net/9RxvM/4/ – Martin Jan 12 '14 at 14:28
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/

TiiJ7
  • 3,332
  • 5
  • 25
  • 37