Possible Duplicate:
How do I trim a string in javascript?
By using replace method in javascript I am trying to remove the empty space between the start and the end of a string:
Here my code:
Any idea how should I achive the result?
input -> " first second ".replace(/[^\s|\s$]/g, ''); // " "
output -> "first second"
String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.
Using String. To remove duplicate whitespaces from a string, you can use the regular expression \s+ which matches with one or more whitespace characters, and replace it with a single space ' ' .
The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.
To remove all spaces from a string:replaceAll(' ', '') . The replaceAll method returns a new string with all of the matches replaced.
This is called trimming.
You need parentheses instead of brackets in the regular expression, and also a multiplier on the white space specifier to match multiple spaces:
var s = " first second ".replace(/(^\s+|\s+$)/g, '');
Demo: http://jsfiddle.net/Guffa/N7xxt/
Add this at the begining of your script:
// Add ECMA262-5 string trim if not supported natively
//
if (!('trim' in String.prototype)) {
String.prototype.trim= function() {
return this.replace(/^\s+/, '').replace(/\s+$/, '');
};
}
Then use yourString.trim()
to remove spaces at the beginning and at the end of your string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With