Javascript - 从字符串中删除 '\n'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36274626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript - Remove '\n' from string
提问by forloop
var strObj = '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n{"text": true, ["text", "text", "text", "text"], [{ "text", "text" }]}\n\n\n'
I am trying to sanitize a string by stripping out the \n
but when I do .replace(/\\\n/g, '')
it doesn't seem to catch it. I also Google searched and found:
我试图通过去除字符串来消毒字符串,\n
但是当我这样做时.replace(/\\\n/g, '')
它似乎没有抓住它。我也谷歌搜索并发现:
..in accordance with JavaScript regular expression syntax you need two backslash characters in your regular expression literals such as
/\\/
or/\\/g
.
..根据 JavaScript 正则表达式语法,您需要在正则表达式文字中使用两个反斜杠字符,例如
/\\/
或/\\/g
。
But even when I test the expression just to catch backslash, it returns false:
(/\\\/g).test(strObj)
但即使我测试表达式只是为了捕捉反斜杠,它也会返回 false:
(/\\\/g).test(strObj)
RegEx tester captures \n
correctly: http://regexr.com/3d3pe
RegEx 测试器\n
正确捕获:http: //regexr.com/3d3pe
回答by epascarello
Should just be
应该只是
.replace(/\n/g, '')
unless the string is actually
除非字符串实际上是
'\n\n\n...
that it would be
那会是
.replace(/\n/g, '')
回答by Tushar
No need of using RegExhere, use String#trim
to remove leading and trailing spaces.
这里不需要使用正则表达式,用于String#trim
删除前导和尾随空格。
var strObj = '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n{"text": true, ["text", "text", "text", "text"], [{ "text", "text" }]}\n\n\n';
var trimmedStr = strObj.trim();
console.log('Before', strObj);
console.log('--------------------------------');
console.log('After', trimmedStr);
document.body.innerHTML = trimmedStr;
回答by mkaatman
You don't need the backslashes.
你不需要反斜杠。
var strObj = '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n{"text": true, ["text", "text", "text", "text"], [{ "text", "text" }]}\n\n\n';
strObj.replace(/\n/g, '');
This code works as expected.
此代码按预期工作。
"{"text": true, ["text", "text", "text", "text"], [{ "text", "text" }]}"
"{"text": true, ["text", "text", "text", "text"], [{ "text", "text" }]}"