我想知道是否有办法将下面的这两个正则表达式结合起来,或者以另一种方式结合我的两个任务。
1) /(<\/[a-z]>|<[a-z]*>)/g
2) /\s{2,}/g
具体来说,它们用于替换:
This is <b>a test</b> and this <i> is also a test</i>
进入这个:
This is <b> a test </b> and this <i> is also a test </i>
第一个正则表达式用于在每个开始和结束标记之前和之后添加一个空格,第二个正则表达式用于匹配每个要删除的两个或多个空格字符的出现。
这是代码
var inputString = 'This is <b>a test</b> and this <i> is also a test</i>',
spacedTags = inputString.replace(/(<\/[a-z]>|<[a-z]*>)/g, ' $1 '),
sanitizedSting = spacedTags.replace(/\s{2,}/g, ' ')
console.log(sanitizedSting);
和jsfiddle。
我知道这些可以使用 DOM 操作来完成,这可能会更快,但我试图避免这种情况。
谢谢