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

3.3k views Asked by At

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.

2

There are 2 answers

0
Tumen_t On BEST ANSWER

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/

1
Donnie D'Amato On

You'll want to escape the \ character so it's not read as a special character.

var noABCD = str.replace(/ABCD\\/, '');

https://regex101.com/r/UjGI4o/1