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?

Will Reese
  • 2,801
  • 2
  • 15
  • 27

4 Answers4

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);
guest271314
  • 1
  • 15
  • 104
  • 177
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);
Tushar
  • 85,780
  • 21
  • 159
  • 179
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>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
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>");

:)

Nik
  • 709
  • 4
  • 22
  • This answer doesn't work for me. Have you tested it? – Will Reese Oct 09 '15 at 03:39
  • since string `"\W\W\R"` in javascript actually means `"WWR"`, so we can just ignore the backslash ` \ `. See: http://stackoverflow.com/questions/2479309/javascript-and-backslashes-replace. – Nik Oct 09 '15 at 03:43