【问题标题】:Replace null bytes替换空字节
【发布时间】:2017-07-20 15:06:51
【问题描述】:

我想从字符串中替换空字节。但是在替换字符串的空字节 \u0000 之后

let data = {"tet":HelloWorld.\u0000\u0000\u0000\u0000"}
let test = JSON.parse(data).tet.replace("\u0000", "");

我始终遵循价值:

 HelloWorld.[][][][]

这不是数组括号或类似的东西。

我只需要值 HelloWorld。我该怎么做?

好的,解决方案是替换所有字节。

.replace(new RegExp("\u0000", "g"), "");

【问题讨论】:

  • JSON.parse 接受 string 作为输入。你的意思是使用JSON.stringify
  • 什么?你想要HelloWorld. 的值,但你只得到HelloWorld.?什么?
  • @HerrDerb 只是您的浏览器不会显示该 unicode 字符。 '\u0000' 是空字符。

标签: javascript regex typescript


【解决方案1】:

普通的字符串替换只替换第一次出现的地方。

但是通过使用带有 global 标志的正则表达式,它将替换所有出现的情况。

示例 sn-p :

console.log("bar bar".replace("bar","foo"));
console.log("bar bar".replace(/bar/g,"foo"));

let data = {"test":"HelloWorld.\u0000\u0000\u0000\u0000"};

console.log("before: " + data.test);
console.log("before (stringified): " + JSON.stringify(data.test));

// removing all the NULL unicode characters
data.test = data.test.replace(/\u0000/g,'');

console.log("after  (stringified): " + JSON.stringify(data.test));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多