Reputation: 3117
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.
Upvotes: 0
Views: 104
Reputation: 1405
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"
Upvotes: 1
Reputation: 7295
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, ''));
Upvotes: 3
Reputation: 5271
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
.
Upvotes: 3
Reputation: 2917
Just try,
var str = " Text is text ";
str = str.replace(/(^\s+|\s+$)/g, '');
Upvotes: 1
Reputation: 12176
var text = " Text is text ".
var res = text.replace(/(^(\s+)|(\s+)$)/g,function(spaces){ return spaces.replace(/\s/g,"");});
console.log(res);
Try this.
Upvotes: 1