JS中如何去除字符串中的坏字符?

发布于 2024-07-29 21:02:44 字数 133 浏览 7 评论 0原文

我的 JS 使用“stringify()”将一些字符串数据保存到 JSON,但是观察输出的 JSON 字符串,我看到很多奇怪的字符(在键空间之外),例如 NULL 和其他错误字符。 现在我没有这些“坏”字符的列表,那么如何将它们从字符串数据中删除呢?

My JS saves some string data to JSON using "stringify()", but observing the outputted JSON string I see a lot of strange chars (out of keyspace), such as NULLs and other bad chars. Now I don't have a list of these "bad" chars so how can I strip them out of my string data?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青春如此纠结 2024-08-05 21:02:44

如果有一个简单的正则表达式就太好了,但我认为不存在。 据我了解,您仍然希望允许 %$#@ 等字符,但希望禁止其他奇怪的字符,例如制表符和空字符。 如果这是正确的,我相信最简单的方法是循环每个字符并评估字符代码......

function stripCrap(val) {
  var result = '';

  for(var i = 0, l = val.length; i < l; i++) {
    var s = val[i];
    if(String.toCharCode(s) > 31)
      result += s;
  }

  return result;
}

如果你真的想使用正则表达式,白名单方法似乎是必要的。 这将允许所有数字、字母和空格...

val = val.replace(/[^a-z 0-9]+/gi,'');

It would be nice if there was a simple RegEx for that, but I don't think there is. From what I understand, you still want to allow characters like %$#@, etc, but want to disallow other oddball chars like tabs and nulls. If this is correct, I believe the easiest way would be to loop each character and evaluate the char code...

function stripCrap(val) {
  var result = '';

  for(var i = 0, l = val.length; i < l; i++) {
    var s = val[i];
    if(String.toCharCode(s) > 31)
      result += s;
  }

  return result;
}

If you really want to use RegEx, a whitelist approach seems necessary. This will allow all numbers, letters, and a space...

val = val.replace(/[^a-z 0-9]+/gi,'');
千紇 2024-08-05 21:02:44

如果您有一个“好”字符列表,您可以创建一个正则表达式来匹配列表中的任何字符,并删除它匹配的任何内容 - 例如,以下正则表达式匹配任何不匹配的内容 字母“a”、“q”或“z”:

/[^aqz]+/ig

If you have a list of the "good" chars you could create a regex which matches any character not in your list, and strip anything it matches - for instance, the following regex matches anything not the letters "a", "q", or "z":

/[^aqz]+/ig
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文