如何删除字符串中的多余空格? [英] How to remove the extra spaces in a string?

查看:53
本文介绍了如何删除字符串中的多余空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用javascript将this containsSpaces变成this contains空格的函数是什么?

What function will turn this contains spaces into this contains spaces using javascript?

我尝试了以下操作,使用类似的 SO 问题,但无法使其正常工作.

I've tried the following, using similar SO questions, but could not get this to work.

var string = " this contains   spaces ";

newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
newString = string.replace(/ +/g,'');  //"thiscontainsspaces"

是否有一种简单的纯 javascript 方法来完成此操作?

Is there a simple pure javascript way to accomplish this?

推荐答案

离你很近了.

请记住,replace 替换 找到的文本与第二个参数.所以:

Remember that replace replaces the found text with the second argument. So:

newString = string.replace(/\s+/g,''); // "thiscontainsspaces"

查找任意数量的连续空格并删除它们.尝试用一个空格代替它们!

Finds any number of sequential spaces and removes them. Try replacing them with a single space instead!

newString = string.replace(/\s+/g,' ').trim();

这篇关于如何删除字符串中的多余空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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