rgajrawala
rgajrawala

Reputation: 2188

Stripping spaces with RegEx

I would like to remove one or more space characters using regular expression.

Input:

hello                        world

Desired Output:

helloworld

Upvotes: 0

Views: 168

Answers (2)

epascarello
epascarello

Reputation: 207557

Looking at your code it should be producing

helloworl

and not hello

The d would be chopped off because of the -1 in the for loop comparison. It should not be there. Your code running fine with the -1 removed: http://jsfiddle.net/3Hjq5/

But why are you looping? A simple regular expression can do it.

function removeSpaces(str) {
    return str.replace(/\s+/g,"");
}

Running example of reg expression: http://jsfiddle.net/3Hjq5/1/

Upvotes: 1

Paul S.
Paul S.

Reputation: 66404

Just use a RegExp replace on the string

'hello                        world'.replace(/\s+/g, ''); // "helloworld"

\s means whitespace
+ means "one or more"
g means "global", as in "match multiple times"

Upvotes: 3

Related Questions