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.
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.
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, ''));
var text = " Text is text ".
var res = text.replace(/(^(\s+)|(\s+)$)/g,function(spaces){ return spaces.replace(/\s/g,"");});
console.log(res);
Try this.
Just try,
var str = " Text is text ";
str = str.replace(/(^\s+|\s+$)/g, '');
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"