用于删除空格的正则表达式 [英] Regular expression for removing whitespaces

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

问题描述

我有一些看起来像这样的文字-

I have some text which looks like this -

"    tushar is a good      boy     "

我要使用javascript删除字符串中所有多余的空格.

Using javascript I want to remove all the extra white spaces in a string.

结果字符串不应包含多个空格,而只能包含一个空格.此外,开头和结尾根本不应该有任何空格.所以我的最终输出应该是这样-

The resultant string should have no multiple white spaces instead have only one. Moreover the starting and the end should not have any white spaces at all. So my final output should look like this -

"tushar is a good boy"

我目前正在使用以下代码-

I am using the following code at the moment-

str.replace(/(\s\s\s*)/g, ' ')

这显然失败了,因为它不处理字符串开头和结尾的空格.

This obviously fails because it doesn't take care of the white spaces in the beginning and end of the string.

推荐答案

这可以在单个 String#replace 调用中完成:

This can be done in a single String#replace call:

var repl = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");

// gives: "tushar is a good boy"

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

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