[英]Replace substring using regex but preserve spaces
I am replacing content in a string with a predetermined character based on if the substring is wrapped in quotes.我根据 substring 是否用引号括起来,用预定字符替换字符串中的内容。
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);
}
Output: The xxxxx brown xxx xxxxx over the xxxxxxxx Output:xxxxx棕色xxxxxxxx超过xxxxxxxx
However I was to preserve the space within lazy dog
但是我要保留
lazy dog
内部的空间
So it would output: The xxxxx brown xxx xxxxx over the xxxx xxx所以它会 output: The xxxxx brown xxx xxxxx over the xxxx xxx
What am I missing to do this?我错过了什么?
You can use another replace
for non space characters instead of "x".repeat
您可以使用另一个
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.