2

I need to remove all the white spaces before the first character (which is not a white space) and remove all the white spaces after the last character (which is not a white space).

Looks like this:

'                 a boat has an anchor       '

Should be 'a boat has an anchor'

'   $$%&@$&$%& lollerskates #372734§     '

Should be '$$%&@$&$%& lollerskates #372734§'

Please ignore the single quotes, they are there to show the white space.

Shazboticus S Shazbot
  • 1,289
  • 2
  • 16
  • 27

2 Answers2

8
string.replace(/^\s+|\s+$/g, "");
Ankit Tyagi
  • 2,381
  • 10
  • 19
  • What would it be if I wanted to remove all spaces that exist after the last character except for one (also keep the remove all white spaces before first character)... so it looks like 'bobby has a boat ' <--wrote nbsp; because stackoverflow removes my white space – Shazboticus S Shazbot Nov 06 '13 at 17:57
  • @ShazboticusSShazbot You could use `string.replace(/^\s+|(\s)\s+$/g, "$1");` or `string.replace(/^\s+|\s+(?=\s$)/g, "")` if you understand lookaheads. – Jerry Nov 06 '13 at 18:25
6

There is a native method for this. string.trim

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

var orig = "   foo  ";

alert( orig.trim() );
posit labs
  • 8,951
  • 4
  • 36
  • 66