ReplaceAll 以清理字符串

ReplaceAll to clean string

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

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

有更好的方法吗?

如有任何建议,我们将不胜感激。

提前致谢

您可以清理代码并在成对数组中定义替换项,然后使用 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 所提到的,最好使用库来解析 non-standard JSON 数据(如果这是您想要做的)。