用于匹配字符串中的单词或短语以进行替换的正则表达式或算法

时间:2014-02-12 04:32:31

标签: javascript regex arrays angularjs

我有一个句子(字符串)和一个字符串数组,这些字符串是句子中包含的单词或短语。

数组中的每个单词或短语都是大写的。数组中单词或短语的索引对应于句子中的序列。例如:

var sentence = "Yes. I know him from my neighborhood. Come in!",
    phrases  = ["YES", "I", "HIM", "NEIGHBORHOOD", "COME IN"],
    result   = "";

我想要做的是匹配句子中的每个单词或短语,并用标签中包含的单词或短语替换它。这将允许用户单击该单词并查看有关该单词的信息(已编写的应用程序的另一部分)。我希望在一个循环内完成此操作。如果没有正则表达式或辅助循环,我就无法实现,例如" I"和文章" AN"或" A"经常在单词中匹配。

// expected
result = "<span>Yes</span>. <span>I</span> know <span>him<span> from my <span>neighborhood</span>. <span>Come in</span>!";

2 个答案:

答案 0 :(得分:2)

您可以使用RegExp构造函数创建动态正则表达式并使用replace:

var sentence = "Yes. I know him from my neighborhood. Come in!",
    phrases  = ["YES", "I", "HIM", "NEIGHBORHOOD", "COME IN"];

var regex = RegExp('\\b('+ phrases.join('|') +')\\b', 'gi');
var result = sentence.replace(regex, '<span>$&</span>');

答案 1 :(得分:-1)

使用替换方法。

var str = "Apples are round, and apples are juicy.";
var newstr = str.replace("apples", "oranges", "gi");
print(newstr);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace