簡體   English   中英

替換與正則表達式匹配的文本中的單詞

[英]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匹配的值?

這很好

查看String.prototype.replace定義

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.

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