0

For example : I have a string like that: " Text is text ".

Now i want to use Javascript to remove all space before and ending of that string to have result :

"Text is text".

How can I that with Javascript. Thank for your help.

Hai Tien
  • 2,929
  • 7
  • 36
  • 55

5 Answers5

3

You can use JavaScript built in function .trim. It is not supported on IE 8 and below, however.

If you need to support older browsers, use jQuery .trim.

Denis
  • 5,061
  • 1
  • 20
  • 22
3

Use String.trim (IE 9+ and normal browsers).

" my text ".trim(); // "my text"

To make sure it will work in all browsers you can use a regular expression:

var str,
    re;
str = " my text ";
re = /^\s+|\s+$/g;

console.log(str.replace(re, ''));

DEMO

Eugene Naydenov
  • 7,165
  • 2
  • 25
  • 43
1
var text = " Text is text ".

var res = text.replace(/(^(\s+)|(\s+)$)/g,function(spaces){ return spaces.replace(/\s/g,"");});

console.log(res);

Try this.

karthick
  • 11,998
  • 6
  • 56
  • 88
1

Just try,

var str = " Text is text ";
str = str.replace(/(^\s+|\s+$)/g, '');
Ajith S
  • 2,907
  • 1
  • 18
  • 30
1

You can use str.trim() spaces at the end and beginning , if you want unwanted spaces in between words u can use regex to remove that

" my text ".trim(); => "my text"
" my       text".replace("/ {2,}/g"," "); => "my text"
" my      text   ".trim().replace("/ {2,}/g"," "); => "my text"
Rijo Joseph
  • 1,375
  • 3
  • 17
  • 33