Search code examples
javascriptregexregexp-replace

Javascript replace regexp \\n with \n, \\t with \t, \\r with \r and so on


I'm having an HTML Input field where the user can enter a delimiter.

This delimiter can include \n, \t, \r and so on. When I append the delimiter to a string in javascript it is appended as \n instead of as a newline character.

While I can use str.replace(/\\n/g, "\n") and so on to replace one variation it does not work if I write a general catch-all regexp like str.replace(/\\([a-z])/g, "\$1") since this just replaces \n with \n again.

How do I have to rewrite the RegExp to replace all double backslashes in front of a character?


Solution

  • There is no shortcut to replace literals with escaped sequences but you may be able to use this:

    const cmap = {'n': '\n', 't': '\t', 'r': '\r'}
    
    var str = `value1\rvalue2\tvalue3\nvalue4`
    
    str = str.replace(/\\([nrt])/g, m => {return cmap[m[1]]})
    
    console.log(str)