如何在javascript中使用替换正则表达式数组[重复]

时间:2022-08-17 15:44:32

This question already has an answer here:

这个问题在这里已有答案:

So I want to take in a string, and test for a series of possible words that might be contained in that string, and if any of those words do occur in the string, i want to replace those with a specific word, in this case "is".

所以我想接受一个字符串,并测试可能包含在该字符串中的一系列可能的单词,如果字符串中出现任何这些单词,我想替换那些具有特定单词的单词,在这种情况下“是”。

function replace_is (string) {
    var exps = [/looks/, /appears/, /seems/, /feels/];
    for(i = 0;i<exps.length;i++) {
        if (string.search(exps[i])==-1) {
            continue;
        }
        else {
            string.replace(exps[i], "is")
            return string;
        }
    }
    return false;
}

Problem is, this does not work. What is a better way to do this? Or why might this not be working?

问题是,这不起作用。有什么更好的方法呢?或者为什么这不起作用?

1 个解决方案

#1


1  

I don't believe string.replace modifies string, so, you should just:

我不相信string.replace会修改字符串,所以,你应该只是:

return string.replace(exps[i], "is");

#1


1  

I don't believe string.replace modifies string, so, you should just:

我不相信string.replace会修改字符串,所以,你应该只是:

return string.replace(exps[i], "is");