首页 > 解决方案 > 如何在不触及引号内的单词和字母的情况下替换字符串中的特定字母

问题描述

如果空格在引号内,我正在尝试替换字符串中的所有空格。我希望引号内的文字根本不被触及。我知道这一点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 '+")

标签: javascriptregex

解决方案


作为正则表达式的替代方案(可能提供更好的解决方案),您可以遍历字符串并推断,每一次奇怪的引用都标志着引用句子的开始:

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('\'')

推荐阅读