Javascript 如何在不接触引号内的单词和字母的情况下替换字符串中的特定字母
我试图替换字符串中的所有空格,除非空格在引号内。我希望引号内的文字根本不被触动。 我知道这个Javascript 如何在不接触引号内的单词和字母的情况下替换字符串中的特定字母,javascript,regex,Javascript,Regex,我试图替换字符串中的所有空格,除非空格在引号内。我希望引号内的文字根本不被触动。 我知道这个regexr!((“+”)|(“.+”)但我不知道如何实现它 const value = " text text ' text in quotes no touch' " value.replaceAll(' ', '+') // wanted results "+text+text+' text in quotes no touch'+" 我的目标 value.
regexr
!((“+”)|(“.+”)
但我不知道如何实现它
const value = " text text ' text in quotes no touch' "
value.replaceAll(' ', '+')
// wanted results "+text+text+' text in quotes no touch'+"
我的目标
value.replaceAll(如果!(“+”)|(“.+”)(“.+”))然后将“”更改为“+”
除了正则表达式(可能提供更好的解决方案),您可以遍历字符串并推断,引号的每一次奇数相遇都标志着引号句子的开始:
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('\'')
除了正则表达式(可能提供更好的解决方案)之外,您还可以遍历字符串并推断,引号的每一次奇遇都标志着引号句子的开始:
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('\'')
您可以使用表达式
字符串或空格
和回调函数,该函数仅在匹配为空格时返回+
:
const value=“文本”“引号中的文本不可触摸”
const repl=value.replace(/'.+?'|/g,m=>m==''?'+':m)
console.log(repl)
您可以使用表达式字符串或空格
和回调函数,该函数仅在匹配为空格时返回+
:
const value=“文本”“引号中的文本不可触摸”
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)
或者,您可以先拆分字符串,然后仅对不以引号开头的子字符串应用替换:
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)
如果引号中的字符串可能包含转义引号,会发生什么情况?例如,
“你会不会”
?@andlrc:updated@georg太好了,谢谢你,你知道当我有一个后面有空格的数字时,只返回数字吗?“12+1”。替换(/(\d)(+)/g,(m,r=>$1);
$1
我的意思是我只想返回regexr@AliHusham:“12+1”。替换(/\D/g,”)
为您提供121
如果引号中的字符串可能包含转义引号,会发生什么情况?例如,“您不会吗”
?@andlrc:updated@georg太好了,谢谢你,你知道当我有一个后面有空格的数字时,只返回数字吗?“12+1”。替换(/(\d)(+)/g,(m,r=>$1);
$1
我的意思是我只想返回regexr@AliHusham:“12+1”。替换(/\D/g,”)
为您提供121
请添加解释以提高洞察力,并为OP提供更多信息information@ucMedia我有点不情愿,因为有更好的答案,但我现在无论如何都这么做了。谢谢,请添加一个解释,以提高洞察力,并给作品更多information@ucMedia我有点不情愿,因为这是更好的答案,不过我现在已经做了。谢谢