Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript replace() Method: remove empty space just at the end and at the beginning of the string [duplicate]

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"
like image 239
Giorgio Cuscela Avatar asked Aug 22 '12 12:08

Giorgio Cuscela


People also ask

How do you remove whitespace from the beginning and end of 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 does replace method work in JavaScript?

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.

How do you remove spaces from a string in JavaScript?

To remove all spaces from a string:replaceAll(' ', '') . The replaceAll method returns a new string with all of the matches replaced.


2 Answers

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/

like image 179
Guffa Avatar answered Oct 21 '22 17:10

Guffa


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.

like image 3
Alejandro Rizzo Avatar answered Oct 21 '22 17:10

Alejandro Rizzo