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.

1

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

2 Comments

You mean String.prototype.trim(), String.trim() will give you TypeError.
I mean method trim of class String.
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.

Comments

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.

Comments

1

Just try,

var str = " Text is text "; str = str.replace(/(^\s+|\s+$)/g, ''); 

Comments

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" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.