javascript - 使用正则表达式替换子字符串但保留空格
问题描述
我根据子字符串是否用引号括起来,用预定字符替换字符串中的内容。
const string = "The \"quick\" brown \"fox\" 'jumps' over the 'lazy dog'";
const pattern = /(?:'([^']*)')|(?:"([^"]*)")/g;
const redactedText = string.replace(pattern, (str) => {
const strippedString = str.replace(/['"]+/g, '');
return 'x'.repeat(strippedString.length);
}
输出: xxxxx brown xxx xxxxx over the xxxxxxxx
但是我要保留里面的空间lazy dog
所以它会输出:xxxx brown xxx xxxxxx over the xxxx xxx
我错过了什么?
解决方案
您可以将另一个replace
用于非空格字符而不是"x".repeat
const string = "The \"quick\" brown \"fox\" 'jumps' over the 'lazy dog'";
const pattern = /(?:'([^']*)')|(?:"([^"]*)")/g;
const redactedText = string.replace(pattern, (str) => {
const strippedString = str.replace(/['"]+/g, '');
return strippedString.replace(/[^\ ]/g,'x'); // replace non space character w/"x"
})
console.log(redactedText)
推荐阅读
- sql - Postgresql 中的特定模式
- java - 想要使用 XSLT 从 Xml 属性中获取价值
- xcode - Xcode 无法在 Swift 中构建测试,因为错误 Cannot find UIImage in scope
- c - Visual Studio 代码 - 调试停止工作 [gdb, mingw, windows 10]
- javascript - 如何通过class或id使用内部标签在纯js中拖放整个元素?
- ruby-on-rails - 如何修复:Mongo::Error::OperationFailure
- python-3.x - 如何在 Mac m1 上使用自制软件安装 python 3.9.6
- python - 我怎样才能使这个 web3 python 脚本更快?
- debian - 无法使用 Snap 方法安装 certbot
- python - 熊猫正常运行时间到日期时间并重置为正常运行时间