Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
15
rated 0 times [  20] [ 5]  / answers: 1 / hits: 93363  / 11 Years ago, mon, august 5, 2013, 12:00:00

I have some text which looks like this -



    tushar is a good      boy     


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(/(sss*)/g, ' ')


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


More From » regex

 Answers
9

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

[#76516] Saturday, August 3, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chase

Total Points: 78
Total Questions: 106
Total Answers: 93

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
chase questions
Thu, Mar 31, 22, 00:00, 2 Years ago
Thu, Jul 1, 21, 00:00, 3 Years ago
Sat, Dec 12, 20, 00:00, 4 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
;