2016-03-17 33 views
-3

下面给出的字符串:如何用JavaScript中的模式替换所有单词?

"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) 
+0

使用string.replace()。 – Quinn

回答

0

使用String.replace()。它可以接受特定的字符串或正则表达式。

相关问题