javascript - 如何在不触及引号内的单词和字母的情况下替换字符串中的特定字母
问题描述
如果空格在引号内,我正在尝试替换字符串中的所有空格。我希望引号内的文字根本不被触及。我知道这一点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('\'')
推荐阅读
- mysql - 如何在一个过程中处理多个游标?
- module - Prestashop 支付模块,处理来自外部服务器的 POST 请求
- javascript - jQuery 选择链接在 Chrome 上不起作用
- javascript - 在页面加载时运行 TamperMokey 脚本
- jsreport - Jsreport XLSX 接收方:将 jsreport 响应保存到 excel 文件
- jmeter - JMeter 将加载时间保存到变量中
- javascript - 如何将对象添加到数组 + Firestore?
- angular - Angular 6 BehaviorSubject“未定义”:错误:TypeError:无法读取我声明的 BehaviorSubject 的属性
- python - 使用一个 .map 调用来使用一个字典更改数据框中多个系列/列的值
- html - 如何制作响应式引导下拉按钮?