Reputation: 709
Javascript doesn't support lookbehinds in regexes. How do I convert the following PHP regex to Javascript?
regPattern="(?<!\\)\\x"
Here is the test case (in Node.js):
var str = '{"key":"abc \\x123 \xe2\x80\x93 xyz"}'
var newStr = str.replace(/regPattern/g, '\\u')
console.log(newStr); // output: '{"key":"abc \\x123 \ue2\u80\u93 xyz"}'
\\x123
doesn't match because it contains \\x
, but \x
matches.
Upvotes: 0
Views: 165
Reputation: 600
Try this:
var newStr = str.replace(/([^\\]|^)\\x/g, '$1\\u');
In other words, match the ^
(start of string) or any non-\
character, followed by \x
, capturing the first character in capture group 1.
Then replace the whole 3-character matched group with capture group 1, followed by \u
.
For example, in abc?\x
, the string ?\x
will be matched, and capture group 1 will be ?
. So we replace the match (?\x
) with $1\u
, which evaluates to ?\u
. So abc?\x
-> abc?\u
.
Upvotes: 1