Tom Rider
Tom Rider

Reputation: 2815

string method replace is not working properly

I am using replace method of string,

     var text = this ex is not working.;
     text = text.replace(" ", "+");
     alert(text);

and got alert :

     this+ex is not working.

Whats the problem here?

Upvotes: 0

Views: 135

Answers (2)

Tats_innit
Tats_innit

Reputation: 34117

Try this: lil diff demo http://jsfiddle.net/bLaZu/6/

Please note:

The g flag on the RegExp, it will make the replacement globally within the string.

If you keen: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

Rest feel free to play around with demo, :)

code

var text = "this ex is not working.";
     text = text.replace(/\s+/g, '+');
     alert(text);​

Upvotes: 2

VisioN
VisioN

Reputation: 145458

To replace all spaces with plus + character use the following:

var text = "this ex is not working.";
text = text.replace(/ /g, "+");
alert(text);

And don't forget to use quotes " for initializing strings.

Upvotes: 1

Related Questions