删除没有\ r \ n的换行符
I'm currently working on a website and doing some JS stuff. I'm fairly new to this topic, so please excuse if my question is stupid:)
我目前正在开发一个网站并做一些JS的东西。我对这个话题相当新,所以请原谅我的问题是愚蠢的:)
I have a JSON string with some line breaks, however I cannot parse it into an JSON object (because of the line breaks) - so I need to remove them and already tried it using
我有一个带有一些换行符的JSON字符串,但我无法将其解析为JSON对象(因为换行符) - 所以我需要删除它们并且已经尝试使用它
stringJSON.replace(/(\r\n|\r|\n)+/, '');
However, this doesn't work, when I do an alert on the string the line breaks are still included.
但是,这不起作用,当我对字符串发出警报时,仍然包括换行符。
Do you have any suggestions?
你有什么建议吗?
Thanks in advance,
提前致谢,
Wiwi :)
JSON:
[
{
"key0": "value 0",
"key1": "value 1",
"key2": "value 2"
},
{
"key0": "value 0",
"key1": "value 1",
"key2": "value 2"
}
]
1 个解决方案
#1
1
You should assign the result of the replace to the stringJSON variable if what you really mean to do is to update the stringJSON variable.
如果你真正想要做的是更新stringJSON变量,你应该将replace的结果赋给stringJSON变量。
stringJSON = stringJSON.replace(/(\r\n|\r|\n)+/g, '');
Replace doesn't change the original string because strings are immutable in Javascript.
替换不会更改原始字符串,因为字符串在Javascript中是不可变的。
Note: The global flag on the regex (g) allows it to match more than once. Without that flag, only the first line break would be replaced.
注意:正则表达式(g)上的全局标志允许它匹配多次。没有该标志,只会替换第一个换行符。
更多相关文章
- 使用append方法将对象转换为字符串
- javascript变量:全局?还是局部?这个得注意
- 在Javascript / node.js中共享模块之间的变量?
- $.each遍历JSON字符串和 Uncaught TypeError: Cannot use 'in' o
- 如何在python中使用命名组和datadict从正则表达式模式中组合字符
- 字符串压缩 牛客网 程序员面试金典 C++ Python
- 求助:Python是否可以用一行代码来同时给变量赋值并打印变量的值
- Python 用hashlib求中文字符串的MD5值
- Python基础(4) - 变量