1

Is there a way to make this string:

foo
    bar

Appear like this:

foo\r\n\tbar

It would really help with debugging a lexer.

2 Answers2

2

The key is to escape \n in a string replace.

let specialCharacters = [
    {regex: /\n/g, replacement: '\\n'},
    {regex: /\t/g, replacement: '\\t'}
];

function escapeSpecialCharacters(str){
  specialCharacters.forEach(c => {
    str = str.replace(c.regex, c.replacement);
  });
  return str;
}

console.log(escapeSpecialCharacters(`test
test
test
1234`));
Jonathan Wilson
  • 4,138
  • 1
  • 24
  • 36
  • right, right, but is there a way to just show all the special characters without manually replacing every single one of them? – Mateusz Sowiński Dec 07 '18 at 21:45
  • There is a finite number of them, and it's not even that large, unless you're counting Unicode symbols. – Kresimir Dec 07 '18 at 21:46
  • 1
    As far as I know, 'special characters' is not some canonical class of characters that has a well-known definition. Why not make a list of all the special characters you care about.. that would be easier I think. – Jonathan Wilson Dec 07 '18 at 21:46
  • There, I've added the means for you to extend my solution with more special characters. Also, I've fixed my solution so that it replaces *all* occurrences of a special character. Before, it was replacing only the first occurrence. – Jonathan Wilson Dec 07 '18 at 21:54
0

If debugging is all you want to do, you can display all escaped characters it in the browser console, but putting the string into an array:

let string = "test\ntest";

let arr = [];

arr.push(string);

console.log(arr);

But that will not change your string in any way, it still contains new line, instead of "\n".

Kresimir
  • 777
  • 5
  • 20