2

In my application i want to remove the unwanted space from starting and ending.And also if there have more than space between words also remove them leaving one space. How can i do this?

Kichu
  • 3,284
  • 15
  • 69
  • 135
  • possible duplicate of [trim in javascript ? what this code is doing?](http://stackoverflow.com/questions/3387088/trim-in-javascript-what-this-code-is-doing) – JohnP Dec 05 '11 at 10:17

3 Answers3

4

Try this:

//remove leading spaces
content = content.replace(/^\s+/g,'');
//remove trailing spaces
content = content.replace(/\s+$/g,'');
//remove whitespaces in the middle
content = content.replace(/\s+/g,' ');
jerjer
  • 8,694
  • 30
  • 36
1

This should work to remove leading and trailing spaces, and reduce two or more spaces to a single space:

str.replace(/^\s+|\s+$/, '').replace('/\s\s+/', ' ')
pgl
  • 7,551
  • 2
  • 23
  • 31
1

You can use jQuery trim method.This function remove all new lines and all spaces leading or trailing from input string.

var str = '          it is a test string                ';

alert($.trim(str));
stealthyninja
  • 10,343
  • 11
  • 51
  • 59
AbTheAsk
  • 88
  • 1
  • 1
  • 4