簡體   English   中英

如何在不觸及引號內的單詞和字母的情況下替換字符串中的特定字母

[英]How to replace specific letters in string without touching the words and letters inside quotes

如果空格在引號內,我正在嘗試替換字符串中的所有空格。 我希望引號內的文字根本不被觸及。 我知道這個regexr .((".+")|('.+'))但我不知道如何實現它。

const value = " text text ' text in quotes no touch' "
value.replaceAll(' ', '+')
// wanted results "+text+text+' text in quotes no touch'+"

我的目標value.replaceAll(if.((".+")|('.+')) then change ' ' to '+")

作為正則表達式的替代方案(可能提供更好的解決方案),您可以遍歷字符串並推斷,每一次奇怪的引用都標志着引用句子的開始:

value.split("'").map((line, index) => {
    if (index % 2 == 0)
        // Even encounters of a quote --> We are outside a quote, so we replace
        return line.replaceAll(' ','+')
    else
        // Odd encounters --> We are inside a quote, so do nothing
        return line 
}).join('\'')

您可以使用表達式string OR space和回調 function 僅當匹配是空格時才返回+

 const value = " text text ' text in quotes no touch' " const repl = value.replace(/'.+?'| /g, m => m === ' '? '+': m) console.log(repl)

要處理轉義引號,“字符串”部分可以細化為'(\\.|[^'])+'

 const value = " text text ' text in \\' quotes no touch' " const repl = value.replace(/'(\\.|[^'])+'| /g, m => m === ' '? '+': m) console.log(repl)

作為替代方案,您可以先拆分字符串,然后僅將替換應用於不以引號開頭的子字符串:

const value = " text text ' text in quotes no touch' "

const splits = value.split(/('.+')/g)   // [" text text ", "' text in quotes no touch'", " "]

const replaced = splits.map(substr => 

  substr.startsWith("'") ? substr : substr.replaceAll(" ", "+")

  ).join("")

console.log(replaced)

暫無
暫無

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

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