0

How can I replace in my string \\ to \? For example, I want to convert RegExp('\\\\b') to RegExp('\\b'). I've tried:

 mystring.replace('\\','\'');
3
  • 4
    Possible duplicate of JavaScript backslash (\‌) in variables is causing an error Commented Aug 6, 2016 at 13:59
  • Its not duplicated, I just need to replace, is there anyway to it? Commented Aug 6, 2016 at 14:11
  • 2
    It's the duplicate. Read the answer. Commented Aug 6, 2016 at 14:11

1 Answer 1

3

If you need to replace all of the occurrences of two backslashes in a row into a single backslash, you use a regular expression with the g flag. Because backslashes are special in regular expressions, you have to escape them (with another backslash). You also have to use the return value of replace:

var str = "Here: \\\\ and here \\\\";
console.log(str);
str = str.replace(/\\\\/g, "\\");
console.log(str);

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

3 Comments

can't we replace with empty string
It just work when I have "\\\\" if I have just 2 slashes it didnt work /:
@TiagoCastro: If you have just two backslashes in a string literal, you have one backslash in the string, not two. See this answer on the question nicael pointed to.

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.