0

I have a question about the replace backlash pattern with JavaScript replace method.

var display_user = "mycompany\bobandalice";
display_user = display_user.replace(/\\/g,"\\\\");
document.write(display_user);

I am hoping to substitute the backslash in the display_user with two back slashes so the document.write displays "mycompany\bobandalice" on the display.

Instead it displays "mycompanyobandalice".

What am I doing wrong ? (Thanks for your help)

1
  • 1
    Your string doesn't have a backslash in it, you have to escape it. "mycompany\\bobandalice" Commented Apr 26, 2016 at 0:17

2 Answers 2

2

The display_user variable does not have the backslash literal at all, so you have nothing to replace.

When "mycompany\bobandalice" string is evaluated the \b sequence is interpreted as a backspace.

So the replace does not replace anything because it's too late - the backslash is not and honestly - was not there ever.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Zerkms - this snippet is from a real life example where the value assigned to display_user does have a single backslash in the value which is returned from an firewall in the meta pattern <domain name><single backslash><user name>.
@bobwilmes okay. Not sure what it changes though.
0

The display_user string doesn't actually have a backslash character. Try escaping the backslash. Something like this:

var display_user = "mycompany\\bobandalice"; 
//                           ^ notice the escaped backslash 
display_user = display_user.replace(/\\/g, '&#92;');

1 Comment

Thank you @Amous - unfortunately the value is actually being passed to the code by a firewall in the meta pattern <domain><single backslash><username>. I'm trying to edit the single backslash to a double backslash to make the meta pattern variable displayable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.