正则表达式用一个空格替换多个空格 [英] Regex to replace multiple spaces with a single space

查看:36
本文介绍了正则表达式用一个空格替换多个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个字符串:

"The dog      has a long   tail, and it     is RED!"

可以使用哪种 jQuery 或 JavaScript 魔法来将空格限制为最多一个空格?

What kind of jQuery or JavaScript magic can be used to keep spaces to only one space max?

目标:

"The dog has a long tail, and it is RED!"

推荐答案

鉴于您还想覆盖制表符、换行符等,只需将 ss+ 替换为 ' ':

Given that you also want to cover tabs, newlines, etc, just replace ss+ with ' ':

string = string.replace(/ss+/g, ' ');

如果您真的只想覆盖空格(因此不想覆盖制表符、换行符等),请这样做:

If you really want to cover only spaces (and thus not tabs, newlines, etc), do so:

string = string.replace(/  +/g, ' ');

这篇关于正则表达式用一个空格替换多个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆