3

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.

1 Answers1

4

Instead of .match you can use .replace:

var s = '596d396962334a76';

var r = s.replace(/../g, '\\x$&');

console.log(r);

RegEx Demo

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