此字符串具有需要删除的正则表达式字符类。以及将多个空间减少为单个空间。
我可以连锁,replace()
但想问一问是否可以建议一个正则表达式代码一次完成整个工作。如何做呢?谢谢
“ \ n \ t \ t \ t \ n \ n \ t \ n \ t \ t \ t食物和饮料\ n \ t \ n”
这是必需的:
“食品和饮料”
var newStr = oldStr.replace(/[\t\n ]+/g, ''); //<-- failed to do the job
您要删除所有前导和尾随空格(空格,制表符,换行符),但将空格保留在内部字符串中。您可以使用空格字符类\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)不存在,但填充工具基本上是.replace(/^\s+|\s+$/g, '')
(具有增加了几个其他字符)反正。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句