bobwilmes
bobwilmes

Reputation: 64

Javascript regex replace with escaped backslash

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)

Upvotes: 0

Views: 76

Answers (2)

Amous
Amous

Reputation: 514

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, '\');

Upvotes: 0

zerkms
zerkms

Reputation: 255155

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.

Upvotes: 2

Related Questions