2

I have this string: "\W\W\R\"

I want to use regex to produce this string: <span>W</span><span>W</span>\R

Here is my code:

"\W\W\R".replace(/\\W/g, "<span>W</span>");

Because the pattern "\W" is a character class, none of the escaping I'm trying to do is responding. How should this be written?

2
  • 1
    It works see regex101.com/r/xE7fG0/2 Commented Oct 9, 2015 at 3:10
  • It doesn't work on the command line though Commented Oct 9, 2015 at 3:14

4 Answers 4

1

The \ in the string is used to escape the special characters following it, so your string \W\W\R is treated as WWR.

When run on command line

> '\W\W\R'
WWR

Double escape the slashes in the string

var str = "\\W\\W\\R".replace(/\\W/g, "<span>W</span>");
console.log(str);

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

Comments

1

The problem is not the regex, it is your string, in string \ is a escape character, so if you want \W\W\R then your string literal should be "\\W\\W\\R" SO

var res = "\\W\\W\\R".replace(/\\W/g, "<span>W</span>");
snippet.log(res)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Comments

1

Try RegExp constructor new RegExp("(\W)|(R$)", "g") return replacement string from ternary match === "W" ? "<span>" + match + "</span>" : "\\" + match within .replace() function

var str = "\W\W\R" , res;
res = str.replace(new RegExp("(\W)|(R$)", "g"), function(match) {
  return match === "W" ? "<span>" + match + "</span>" : "\\" + match
});
console.log(res);
document.write(res);

Comments

0

simply ensure that the character matched is actually the capital letter 'W' by wrapping it in a square bracket []

"\W\W\R".replace(/[W]/g, "<span>W</span>");

:)

2 Comments

This answer doesn't work for me. Have you tested it?
since string "\W\W\R" in javascript actually means "WWR", so we can just ignore the backslash ` \ `. See: stackoverflow.com/questions/2479309/….

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.