要删除所有开头和结尾的空格(空格,制表符,换行符),但保留内部字符串中的空格。您可以使用空格字符类\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, '')
(加上一些其他字符)。
不要忘记,替换空格将替换_all_空格。 –
我不会在一个替换,但我认为这是可能的。它更清楚使用一个正则表达式去除字符,一个用于保留单个空格,另一个用于修剪。 –