Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove last and first spaces from a string? [duplicate]

Tags:

javascript

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 ?

like image 800
xRobot Avatar asked May 30 '12 07:05

xRobot


People also ask

How do you remove the first and last space in a string?

String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.

How do you remove duplicate spaces in a string?

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 ' ' .

How can I remove the trailing spaces from a string in C++?

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.

How do I remove extra spaces from a string in Java?

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.


1 Answers

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()

like image 136
papaiatis Avatar answered Oct 12 '22 23:10

papaiatis