Possible Duplicate:
How do I trim a string in javascript?
I need to remove only the last and the first spaces from a generic string.
Example:
var str = " hello world "; // become "hello world"
var str = "ehi, do you come from ? "; // become "ehi, do you come from ?"
var str = "I am from Cina"; // remain "I am from Cina"
How can I do that ?
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 ' ' .
We can use a combination of string's find_first_not_of() and find_last_not_of() functions to remove leading and trailing spaces from a string in C++ by finding the index of the first and last non-whitespace character and pass the index to substr() functions to trim the string.
To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
The trim from jQuery is what you are looking for.
$.trim(' string with spaces at the ends ');
Or plain javascript:
' string with spaces at the ends '.trim()
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