简体   繁体   English

jQuery:如何修剪单词之间的新行和制表符

[英]jQuery: How to trim new line and tab characters between words

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. 嗨我在单词之间得到新行(\\ n)和制表符(\\ t)字符,我试图通过使用$.trim()函数来修剪它们但它不起作用。 So can anyone have some solution for this type of problem. 所以任何人都可以为这类问题找到解决方案。

Ex: 例如:

var str = "Welcome\n\tTo\n\nBeautiful\t\t\t\nWorld";
alert($.trim(str));

the above code is not working. 上面的代码不起作用。

str.replace(/\s+/g, " "); //try this

reference replace 参考替换

\\s matches any newline or tab or white-space \\ s匹配任何换行符或制表符或空格

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"

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"

You can use replace with a regular expression : 您可以使用正则表达式 替换

var str = "Welcome\n\tTo\n\nBeautiful\t\t\t\nWorld";
alert($.trim(str.replace(/[\t\n]+/g, ' ')));

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM