I want to add "\x" after every 2 characters on a string, and also in the beginning. For example, the string 596d396962334a76
would become \x59\x6d\x39\x69\x62\x33\x4a\x76
.
I tried this code: "596d396962334a76".match(new RegExp('.{1,2}', 'g')).join("/");
but it gives this error: Uncaught SyntaxError: Invalid hexadecimal escape sequence
.
Asked
Active
Viewed 596 times
3

Dave Horvath
- 53
- 4
-
1That is bacause you tried `.join("\x")`, right? You need two backslashes, `.join("\\x")` – Wiktor Stribiżew Feb 15 '21 at 21:38
-
1You state `add "\x" after every 2 characters`, but your example shows that you want to prefix `\x` to every 2 chars. Which is it? – Peter Thoeny Feb 15 '21 at 21:46
-
4**Wrong Dupe:** How is replacement of backward slash with forward slash same as adding `\x` every 2 words? – anubhava Apr 12 '21 at 06:10
1 Answers
4
Instead of .match
you can use .replace
:
var s = '596d396962334a76';
var r = s.replace(/../g, '\\x$&');
console.log(r);
Here we match any 2 characters using /../g
regex and append \x
before each match by using replacement expression: \\x$&
.

anubhava
- 761,203
- 64
- 569
- 643