2014-01-12 88 views
0

如何在文本字符串中查找数组项目?我不知道该数组,我不知道文本。但是当一个数组项包含在文本中然后派对!jQuery:在文本字符串中查找数组项目

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 +'".'); 
} 

测试:http://jsfiddle.net/9RxvM/

+0

正则表达式应该匹配类似/ \ B(苹果| APE |树)\ B/- 你不需要这里的jQuery在所有 – mplungjan

+0

http://stackoverflow.com/questions/1789945/how-我可以检查,如果一个字符串,包含另一个字符串在JavaScript中 – pathfinder

回答

1

使用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 +'".'); 
} 

请注意,这将获得数组中的第一个匹配项。 要检查是否有匹配的项目,只需检查是否matchedArrayItem!=“”;用正则表达式

+1

http://jsfiddle.net/9RxvM/1/ – Samleo

+0

我怎么能运行这个多个匹配,并替换文本输出和数组串? http://jsfiddle.net/9RxvM/4/ – Martin

+0

@Martin ..为此你需要使用一个数组:http://jsfiddle.net/9RxvM/7/ – Samleo

1

方式一:

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); 

注:我删除了从数组字符串的空间,使其正确的格式

注2:match()返回匹配的数组,所以我拿第一([0])结果。

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

相关问题