【问题标题】:jQuery: Find array items in text stringjQuery:在文本字符串中查找数组项
【发布时间】:2014-01-12 14:05:01
【问题描述】:

如何在文本字符串中查找数组项?

我不知道数组,也不知道文本。但是当文本中包含数组项时,那就派对!

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/

【问题讨论】:

标签: jquery arrays match


【解决方案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 +'".');
}

请注意,这将获得数组中的第一个匹配项。 要检查是否有匹配的项目,只需检查 matchArrayItem!="";

【讨论】:

  • 我怎样才能对多个匹配项运行它并替换文本输出和数组字符串? jsfiddle.net/9RxvM/4
【解决方案2】:

正则表达式的一种方式:

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/

【讨论】:

    猜你喜欢
    • 2011-08-17
    • 2010-10-29
    • 2020-06-19
    • 2013-08-21
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多