Javascript 使用正则表达式替换子字符串,但保留空格

Javascript 使用正则表达式替换子字符串,但保留空格,javascript,Javascript,我将根据子字符串是否用引号括起来,用预先确定的字符替换字符串中的内容 const string = "The \"quick\" brown \"fox\" 'jumps' over the 'lazy dog'"; const pattern = /(?:'([^']*)')|(?:"([^"]*)")/g; const redactedText = string.replace(pattern, (st

我将根据子字符串是否用引号括起来,用预先确定的字符替换字符串中的内容

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上的xxxxx棕色xxxxx

然而,我要在
lazy dog

因此,它将输出: xxxxx棕色的XXXXXXXXX在XXXXXXXX上方


执行此操作时,我缺少什么?

您可以对非空格字符使用另一个
替换
,而不是
“x”。重复

const string=“快速”布朗“狐狸”跳过“懒狗”;
常量模式=/(?:'([^']*))|(?:“([^”]*)”)/g;
常量redactedText=string.replace(模式,(str)=>{
const strippedString=str.replace(/['“]+/g');
返回strippedString.replace(/[^\]/g,'x');//替换非空格字符w/“x”
})
console.log(redactedText)