1

I am replacing content in a string with a predetermined character based on if the substring is wrapped in quotes.

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

However I was to preserve the space within lazy dog

So it would output: The xxxxx brown xxx xxxxx over the xxxx xxx

What am I missing to do this?

1 Answer 1

2

You can use another replace for non space characters instead of "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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.