Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicate white spaces in a string? [duplicate]

Possible Duplicate:
Removing whitespace from string in JavaScript

I have used trim function to remove the white spaces at the beginning and end of the sentences. If there is to much white spaces in between words in a sentence, is there any method to trim?

for example

"abc                  def. fds                            sdff." 
like image 399
Lakshmitha Avatar asked Oct 14 '11 07:10

Lakshmitha


People also ask

How do I get rid of extra white spaces in a string?

The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".

How do I remove repeating words from a string?

We create an empty hash table. Then split given string around spaces. For every word, we first check if it is in hash table or not. If not found in hash table, we print it and store in the hash table.


1 Answers

try

"abc                  def. fds                            sdff."  .replace(/\s+/g,' ') 

or

"abc                  def. fds                            sdff."      .split(/\s+/)      .join(' '); 

or use this allTrim String extension

String.prototype.allTrim = String.prototype.allTrim ||      function(){         return this.replace(/\s+/g,' ')                    .replace(/^\s+|\s+$/,'');      }; //usage: alert(' too much whitespace     here   right?  '.allTrim());    //=> "too much whitespace here right?" 
like image 123
KooiInc Avatar answered Sep 20 '22 12:09

KooiInc