如何在 Javascript 中的字符串的每 2 个单词后添加 "\x"?
How to add "\x" after every 2 words on a string in Javascript?
我想在字符串的每两个字符之后以及开头添加“\x”。例如,字符串 596d396962334a76
将变为 \x59\x6d\x39\x69\x62\x33\x4a\x76
。
我试过这段代码:"596d396962334a76".match(new RegExp('.{1,2}', 'g')).join("/");
但它给出了这个错误:Uncaught SyntaxError: Invalid hexadecimal escape sequence
.
您可以使用 .replace
:
而不是 .match
var s = '596d396962334a76';
var r = s.replace(/../g, '\x$&');
console.log(r);
这里我们使用 /../g
正则表达式匹配任意 2 个字符,并使用替换表达式在每个匹配之前附加 \x
:\x$&
.
我想在字符串的每两个字符之后以及开头添加“\x”。例如,字符串 596d396962334a76
将变为 \x59\x6d\x39\x69\x62\x33\x4a\x76
。
我试过这段代码:"596d396962334a76".match(new RegExp('.{1,2}', 'g')).join("/");
但它给出了这个错误:Uncaught SyntaxError: Invalid hexadecimal escape sequence
.
您可以使用 .replace
:
.match
var s = '596d396962334a76';
var r = s.replace(/../g, '\x$&');
console.log(r);
这里我们使用 /../g
正则表达式匹配任意 2 个字符,并使用替换表达式在每个匹配之前附加 \x
:\x$&
.