繁体   English   中英

如何防止这种用空格替换连字符的正则表达式也用其他连字符替换连字符?

[英]How to prevent this regex that replaces hyphens with spaces from also replacing hyphens with additional hyphens?

此正则表达式:

str.replace(/ +/g, '-').toLowerCase();

将转换为:

The dog jumped over the lazy - chair

到这个:

the-dog-jumped-over-the-lazy---chair

如何修改它,以使其产生此结果(仅单个连字符):

the-dog-jumped-over-the-lazy-chair

我会假设您的实际输入是“狗跳过了懒人-椅子”,连字符周围的空格被转换了,因为没有其他原因可以使模式匹配。

尝试这个:

str.replace(/( +- *)|(- +)|( +)/g, '-').toLowerCase();

这会明确检查连字符两侧的空格字符串(第一个模式还设计为占用尾随空格),在此过程中恰好消耗了一个连字符。 如果连字符已被空格包围,则该连字符会包含在匹配项中,因此在编写连字符时,它只是一个“替换”; 在这种情况下,只需删除空格,并通过替换操作重新创建连字符,因为连字符被捕获为表达式的一部分。

在正则表达式中包括连字符。

str.replace(/[ -]+/g, '-').toLowerCase();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM