Sandy
Sandy

Reputation: 2613

How to replace \Z from String in javascript

I have a string representing a regex str = "[A-z]\Z"; I want to replace \Z with $ as \Z is not supported in javascript regex.

Is there a way to do this? I tried a few string replace by creating a regex for \Z but they don't work as expected. It also works on any occurrence of Z. Is there a way to achieve this? Here is my sample code which has issue

var expression = "[abczZ]\Z";
var regEx = new RegExp("\\Z", "g"); 
a=  expression.replace(regEx, "\\s");
alert(a);

Upvotes: 0

Views: 1332

Answers (1)

Joey
Joey

Reputation: 354466

You need one additional layer of escaping:

var regEx = new RegExp("\\\\Z", "g");

because you give the regex as a string, so one escape layer will be “eaten” by the string, retaining only \Z for the regex, which matches a literal Z.

You can also use a regex literal, in which case you don't need to double-escape:

var regEx = /\\Z/g;

Of course, to test it on your string you first need to fix your string. As it stands it does not contain any backslash at all. var expression = "[abczZ]\Z" results in expression containing the string "[abczZ]Z" because you did not escape the backslash. Exact same problem as described in the first two paragraphs.

Try it yourself in the JS console:

> "[abczZ]\Z"
"[abczZ]Z"
> "[abczZ]\\Z"
"[abczZ]\Z"
> "[abczZ]\Z".replace(new RegExp("\\\\Z", "g"), "$")
"[abczZ]Z"
> "[abczZ]\\Z".replace(new RegExp("\\\\Z", "g"), "$")
"[abczZ]$"

Upvotes: 4

Related Questions