skip to Main Content

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.

How it looks in VS Code

2

Answers


  1. 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, ''):

    // Using String.raw`` to get string with n treated as raw characters, not newlines, just like if you read data of this form from a file or socket
    const input = String.raw` {n  joy: ["yellow", "orange", "pink"],n  surprise: ["blue", "purple"],n  fear: ["black", "gray"]n};`;
    const badoutput = input.replace(/[n\ ]/g, ''); // Only removes newlines, backslashes and spaces, not literal n
    console.log("Incorrectly filtered string is", badoutput);
    const goodoutput = input.replace(/(\n|[n\ ])/g, '');  // Removes literal n, plus newlines, backslashes and spaces
    console.log("Correctly filtered string is", goodoutput);
    Login or Signup to reply.
  2. 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 remove and whitespaces. Following should work for you:

    text = text.replace(/s|\n?/g, '');
    

    Where s will match any whitespace including line breaks and \n? will match literal n and which would be replaced with empty string.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search