Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  113] [ 2]  / answers: 1 / hits: 94322  / 11 Years ago, fri, june 7, 2013, 12:00:00

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"

Is there a simple pure javascript way to accomplish this?


More From » regex

 Answers
6

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

[#77769] Wednesday, June 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
neildrews

Total Points: 166
Total Questions: 103
Total Answers: 85

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
neildrews questions
Fri, Feb 18, 22, 00:00, 2 Years ago
Tue, Oct 12, 21, 00:00, 3 Years ago
Tue, Mar 23, 21, 00:00, 3 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
;