3
var str = "Hello\\\World\\\";
var newStr = str.replace("\\\", "");
alert(newStr); // I want this to alert: HelloWorld

The number of slashes is always 3, not more not less. How can I replace them? The code above doesn't work at all. I've played around a bit with the global flag, escaping the slashes etc but can't figure it out.

3 Answers 3

3

Firstly, you need to escape each slash with another backslash, as mentioned by @Bathsheba.

Additionally, you want your replacement regex to be global:

var str = "Hello\\\\\\World\\\\\\";
var newStr = str.replace(/\\\\\\/g, "");
alert(newStr); // I want this to alert: HelloWorld
Sign up to request clarification or add additional context in comments.

Comments

1

If you want three slashes in a row in a string literal then you need to escape each one in turn:

var str = "Hello\\\\\\World\\\\\\";
var newStr = str.replace("\\\\\\", "");

In your current string, \\\W would be one slash and an error as \W is not a valid sequence. (Some more examples: \\ is a single slash, \t a tab, \" a quotation character).

1 Comment

it will only replaced the first occurrence...u need to add global modifier..so your regex will be /\\\\\\/g..check this out..jsfiddle.net/RZ6TL..
0

Try this regex \\\\\\ for replace

enter image description here

\\ indicates \

There are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".

If you want to use any of these characters as a literal in a regex, you need to escape them with a backslash.

1 Comment

Thank you! Everything makes sense now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.