字符串用正则表达式替换正则表达式字符类

String replace regex character classes using regex

本文关键字:正则表达式 字符 替换 字符串      更新时间:2023-09-26

这个字符串有需要删除的regex字符类。以及将多个空间缩减为单个空间。
我可以链replace(),但想问是否可以建议一个正则表达式代码一次完成整个工作。怎样才能做到呢?由于

"'n't't' n't' 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/, '');

如果您还想将内部空格减少到单个空格,I 建议使用两个正则表达式并将它们链接起来:

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, '')(添加了几个其他字符)。

我推荐这种模式(假设您想在主字符串中保留'n s或't s):

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

如果你不想保留它们,你可以这样写:

/^['t'n ]+|['t'n]*|['t'n ]+$/g