javascript jQuery:如何修剪单词之间的换行符和制表符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19628942/
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
jQuery: How to trim new line and tab characters between words
提问by Anil Kumar Pandey
Hi I am getting new line(\n) and tab(\t) characters between words and I was trying to trim those by using $.trim()
function but its not working. So can anyone have some solution for this type of problem.
嗨,我在单词之间得到新行(\n)和制表符(\t)字符,我试图通过使用$.trim()
函数来修剪它们,但它不起作用。因此,任何人都可以为此类问题提供一些解决方案。
Ex:
前任:
var str = "Welcome\n\tTo\n\nBeautiful\t\t\t\nWorld";
alert($.trim(str));
the above code is not working.
上面的代码不起作用。
回答by Rituraj ratan
回答by pala?н
You can do this:
你可以这样做:
var str = "Welcome\n\tTo\n\nBeautiful\t\t\t\nWorld";
alert($.trim(str.replace(/[\t\n]+/g,' ')));
// results is "Welcome To Beautiful World"
回答by Paul Draper
That is expected. trim
only takes care of leading and trailing whitespace.
这是预期的。trim
只处理前导和尾随空格。
Instead, use
相反,使用
str.split(/\s/).join(' ');
In your example, this returns
在您的示例中,这将返回
"Welcome To Beautiful World"