Search code examples
javascriptstringsplitsubstrstripping

Javascript passed string with \r in the string is being interpreted to newline


I am receiving a new string like so "ABCD\richard"

I want to be able to strip off "ABCD\" off of the string. However JavaScript is interpreting the "\r" as a new line metacharacters. I imagine I will have the same issues with any metacharacters. I am looking for a way to strip the string of "ABCD\" on all strings passed.

The end result should be "richard" as the final string. This is what I have tried so far:

string.substr(5,100); string.split('ABCD\');

Here is my code:

function export_sal(user)
{
    var noABCD = user.replace(/ABCD\\/, '');
    console.log(noABCD);
}

This is the HTML:

<div class="pull-left" style="padding-bottom:5px;padding-left:5px;">
    <div onclick="export_sal('<?php echo $_SERVER['AUTH_USER'];?>');" class='btn btn-info btn-md' id="e_sal">SAL Export

the result of the console output is like this:

ABCD ichard

I need the console.log output to show: richard

I appreciate the help. Thank you.


Solution

  • You need to escape not only \ but \n, \r, \t for this to work correctly.

    "ABCD\richard".replace("\r", "\\r").replace("\n", "\\n").replace("\t", "\\t").split(/\\/)
    

    https://jsfiddle.net/4c5b5v2k/