remove extra spaces in string javascript

旧时模样 提交于 2019-11-27 13:41:04

问题


what function will turn

 this contains       spaces 
into
this contains spaces
using javascript?

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"


Edited the question to focus more on the javascript aspect. Is there a simple pure javascript way to accomplish this?

回答1:


You're close.

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();



回答2:


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



回答3:


I figured out one way, but am curious if there is a better way...

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



回答4:


Try this one, this will replace 2 or 2+ white space from string.

string.replace(/\s{2,}/g, '')


来源:https://stackoverflow.com/questions/16974664/remove-extra-spaces-in-string-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!