簡體   English   中英

如何替換 JavaScript 中遵循模式的所有單詞?

[英]How to substitute all words following a pattern in 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)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM