首页 > 解决方案 > 使用正则表达式替换子字符串但保留空格

问题描述

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

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

我错过了什么?

标签: javascript

解决方案


您可以将另一个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)


推荐阅读