【问题标题】:How to add "\x" after every 2 words on a string in Javascript?如何在Javascript中的字符串每2个单词后添加“\ x”?
【发布时间】:2021-05-18 19:02:55
【问题描述】:

我想在字符串的每 2 个字符之后添加“\x”,也想在开头添加。例如,字符串596d396962334a76 将变为\x59\x6d\x39\x69\x62\x33\x4a\x76

我试过这个代码:"596d396962334a76".match(new RegExp('.{1,2}', 'g')).join("/");,但它给出了这个错误:Uncaught SyntaxError: Invalid hexadecimal escape sequence

【问题讨论】:

  • 那是因为你试过.join("\x"),对吧?你需要两个反斜杠,.join("\\x")
  • 您声明add "\x" after every 2 characters,但您的示例显示您希望在每2个字符前加上\x。是哪个?
  • Wrong Dupe:用正斜杠替换反斜杠如何与每2个单词添加\x相同?

标签: regex string hex


【解决方案1】:

你可以使用.replace代替.match

var s = '596d396962334a76';

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

console.log(r);

RegEx Demo

这里我们使用 /../g 正则表达式匹配任意 2 个字符,并使用替换表达式在每个匹配之前附加 \x\\x$&

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-28
    • 2017-07-25
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 2011-05-15
    相关资源
    最近更新 更多