如何用JavaScript中的模式替换所有单词?

时间:2016-03-17 14:29:18

标签: javascript regex

给出以下字符串:

"Hello this is a :sample string :hello"

我想用其他内容替换:sample:hello。我怎么能用JavaScript做到这一点?

这就是我的尝试:

var sentence = "Hello this is a :sample string :hello";
var words = sentence.split(" ");
for (var i = 0; i < words.length; i++) {
     if (words[i].startsWith(":")) {
       words[i] = words[i] + ":";
    }
}

sentence = words.join(" ");
console.log(sentence)

1 个答案:

答案 0 :(得分:0)

使用users。它可以接受特定的字符串或正则表达式。