【问题标题】:ReplaceAll to clean stringReplaceAll 清理字符串
【发布时间】:2019-07-10 01:52:02
【问题描述】:

我必须使用几个 replaceAll 函数来清理我的数据。

JSON.parse(data.replaceAll('{\'', '{"').replaceAll('\'}', '"}').replaceAll('\',\'', '","').replaceAll('\': \'', '": "').replace(/[\n\r]+/g, ' ').replaceAll("  ", " "));

有更好的方法吗?

任何建议将不胜感激。

提前致谢

【问题讨论】:

  • 您能否阐明“清理”数据的含义。您希望看到的示例输入/输出格式是什么。
  • 是否有更换订单。当用上面的代码替换时,它也会被替换,已经替换的字符也一样。
  • 考虑使用像 JSON5 这样的库来解析您的非标准 JSON 输入。像这样编写自己的代码可能会导致边缘故障。
  • replaceAll() 来自哪里?这不是本机方法
  • @charlietfl 可能为String.prototype.replaceAll proposal使用了polyfill

标签: javascript jquery regex str-replace replaceall


【解决方案1】:

您可以清理代码并在成对数组中定义替换,然后使用 reduce 对其进行迭代

const replacements = [["{'", '{"'], ["'}", '"}'], ["','", '","'], ["': '", '": "'], ['\n', ' '], ['\r', ' '], ['  ', ' ']];

const data = `{' {'{'{' {' '}'} '}'}  ','',' ',' ': ' ': '': '': '             Hello\n\r\n\n\r\n\n\r\nWorld\n\r`;

const newData = replacements.reduce((a, [token, replacement]) => a.replace(new RegExp(token, 'g'), replacement), data);

console.log(newData);

但正如 Dean Taylor 所提到的,最好使用库来解析非标准 JSON 数据(如果您正在尝试这样做)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多