[英]Replacing words in text that match regex
我正在嘗試替換文本中與給定正則表達式匹配的所有單詞。 我做了一個看起來像這樣的函數:
const str = this.node.body;
const regex = /(href=\')([^\']*)(\')/g;
let newStr;
if (str.match(regex)) {
for(let i = 0; i < str.match(regex).length; i++) {
let url = str.match(regex)[i] + ' target="_blank"';
newStr = str.replace(str.match(regex)[i], url);
}
}
但是,這是不對的,因為在newStr
中將僅替換匹配字符串的最后一個值,因為在循環中總是從str變量中獲取文本,我newStr
到這一點,以便循環瀏覽更新的newStr
,並替換所有與regex
匹配的值?
這很好
const str = this.node.body;
const regex = /(href=\')([^\']*)(\')/g;
let newStr = str.replace(/(href=\')([^\']*)(\')/g, '$& target="_blank"')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.