2016-08-24 286 views
1

该字符串具有需要删除的正则表达式字符类。以及将多个空间减少到单个空间。
我可以连锁replace(),但想过问是否可以建议一个正则表达式代码一次完成整个工作。如何做呢?由于字符串使用正则表达式替换正则表达式字符类

“\ n \ t \ t \ t \ n \ n \ t \ n \ t \ t \ tFood和饮料\ n \ t \ n” 个

这是必要的:

“食品和饮料”

var newStr = oldStr.replace(/[\t\n ]+/g, ''); //<-- failed to do the job 
+0

不要忘记,替换空格将替换_all_空格。 –

+0

我不会在一个替换,但我认为这是可能的。它更清楚使用一个正则表达式去除字符,一个用于保留单个空格,另一个用于修剪。 –

回答

2

要删除所有开头和结尾的空格(空格,制表符,换行符),但保留内部字符串中的空格。您可以使用空格字符类\s作为简写,并匹配或者字符串的开始或结束。

var oldStr = "\n\t\t\t \n\n\t \n\t \t\tFood and drinks \n \t\n"; 

// ^\s+ => match one or more whitespace characters at the start of the string 
// \s+$ => match one or more whitespace characters at the end of the string 
// | => match either of these subpatterns 
// /g => global i.e every match (at the start *and* at the end) 

var newStr = oldStr.replace(/^\s+|\s$/g/, ''); 

如果你也想减少内部空间到一个空间,我推荐使用两个正则表达式和链接它们:

var oldStr = "\n\t\t\t \n\n\t \n\t \t\tFood and  drinks \n \t\n"; 
var newStr = oldStr.replace(/^\s+|\s+$/g, '').replace(/\s+/g, ' '); 

第一.replace()后,所有的前端和后端空白被删除,只留下内部空间。用一个空格替换一个或多个空格/制表符/换行符的运行。

另外一个路要走可能是空白的所有运行减少为单个空格,然后修剪剩余的开头和结尾的空间之一:

var oldStr = "\n\t\t\t \n\n\t \n\t \t\tFood and  drinks \n \t\n"; 

var newStr = oldStr.replace(/\s+/g, ' ').trim(); 
// or reversed 
var newStr = oldStr.trim().replace(/\s+/g, ' '); 

.trim()不存在之前ES5.1( ECMA-262),但polyfill本质上是.replace(/^\s+|\s+$/g, '')(加上一些其他字符)。

2

我建议这种模式(假设你想保持\n如此[R \t在你的主串):

/^[\t\n ]+|[\t\n ]+$/g 

如果你不想让他们,你可以使用这样的事情:

/^[\t\n ]+|[\t\n]*|[\t\n ]+$/g 
+0

我尝试了最后一种模式,因为我不想保留它们,但它在最后留下了新的一行。在控制台中尝试一下,你应该看到。 –

+0

尝试你的第一个删除前导,但留下尾随空格,因为它需要全局选项来同时得到:'oldStr.replace(/^[\ t \ n] + | [\ t \ n] + $/g,' ');' –

+0

修好了,谢谢。 :) –