I am going crazy here.
Using Angular and TypeScript, I fetch some data from OpenAI that when I console.log, it looks like this:
" {n joy: ["yellow", "orange", "pink"],n surprise: ["blue", "purple"],n fear: ["black", "gray"]n};"
I need to remove newline, backslash and whitespace. I use JavaScript replace method to achieve this:
replace(/[n\ ]/g, '');
If you try to test this code in provided snippet, any JS console, or regex101 website, it will display the desired output. However, in my case, the output is always like this:
"{njoy:["yellow","orange","pink"],nsurprise:["blue","purple"],nfear:["black","gray"]n};"
Whitespace and get removed, but the "n" char stays. How to write regex so that output is
"{joy:["yellow","orange","pink"],surprise:["blue","purple"],fear:["black","gray"]};"
const input = " {n joy: ["yellow", "orange", "pink"],n surprise: ["blue", "purple"],n fear: ["black", "gray"]n};"
const output = input.replace(/[n\ ]/g, '');
console.log("Filtered string is", output);
Screenshot shows how the replace method looks in my code.
2
Answers
Your code snippet works just fine. I’m guessing your data contains actual backslashes followed by the letter
n
, not newlines at all. In that case you need to match and replace that two character pattern, not just single characters in a class, e.g..replace(/(\n|[\ ])/g, '')
:Converting my comment to answer so that solution is easy to find for future visitors.
Looks like your input has literal
n
and you want to removeand whitespaces. Following should work for you:
Where
s
will match any whitespace including line breaks and\n?
will match literaln
andwhich would be replaced with empty string.