我正在尝试找出一些 JavaScript 正则表达式来匹配不在 HTML 标记内的最后一个空格。例如,在以下示例中:
// Should match the space between `custom` and `text`
My custom text;
// Should match the space between `a` and `link`
My custom text with <a href="#">a link<a/>.
// Should still match the space between `a` and `link`
My custom text with <a href="#">a link<a/><span style="color: red;">.</span>
我有以下正则表达式( source ,已修改),它选择不在 HTML 标记中的所有空格: (?<!<[^>]*)\s(?<![^>]*<)
,但我不确定如何进一步进行最后一点并仅选择最后一个空格。
起初我以为我可以这样做:(?<!<[^>]*)\s(?<![^>]*<)(?=[^\s]*$)
,但这不适用于我的最后一个示例。
这是a fiddle .
有什么想法吗?
最佳答案
您需要\s+((\S|<[^>]+>)*)$
它查找 1 个或多个空格,后跟 0 个或多个非空格或 html 标签。
看下面的代码片段:
var txt1 = 'My custom text.',
txt2 = 'My custom text with <a href="#">a link<a/>',
txt3 = 'My custom text with <a href="#">a link<a/><span style="color: red;">.</span>';
var reg = new RegExp(/\s+((\S|<[^>]+>)*)$/, 'g');
console.log(txt1.replace(reg, " $1"));
console.log(txt2.replace(reg, " $1"));
console.log(txt3.replace(reg, " $1"));
关于Javascript 正则表达式匹配不在 HTML 标签定义内的最后一个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48940138/