# javascript search and replace single characters



## derektech

I have been trying to use javascript replace() to search and replace special individual characters in a string. But having some difficulties.

the string is something like:

sometext+othertext&moretext?somemoretext=somevalue&sometext+othertext&moretext?somemoretext=somevalue

In the above example string I want to replace all occurences of the following characters:

+, =, ?, &

This is how I tried to do it for each character:

replace("+", "NewText").

But this only replaced the first occurence of the character.

I also tried
replace(/+/g, "NewText"), but it would not allow me to do it.


Any assistance will be much appreciated.


----------



## artur02

Check this site, especially Example 3 - Global Search.


----------



## derektech

artur02 said:


> Check this site, especially Example 3 - Global Search.


thanks, but I have already been to that site. Infact I have the site as a bookmark - the very first place I checked!

The site seems to discuss how to search and replace STRINGS of characters globally.
I need to search and replace SINGLE characters globally.


----------



## cristobal03

If you typed your second attempt literally,



> replace(/+/g, "NewText")


you need quotes around the plus sign.

I'm guessing this is to swap out literals with entity references and vice versa? If you actually tried *replace(/"+"/g, " ")* without result, I think we'll need to see a larger chunk of code.

chris.


----------



## cristobal03

[bump]

Boy, was that incorrect. Nevermind what I said about quotes. I don't know what I was thinking. Can we see a larger code sample (if this is still an issue)?

chris.


----------



## Mosaic1

> The site seems to discuss how to search and replace STRINGS of characters globally.
> I need to search and replace SINGLE characters globally.


 But a string can be a single character. The length is not the issue. That site is correct.

The + is a special character. So to be read as a string and not as a quantifier , you have to type a backward slash in front of it. Like this \+

So let's say I want to replace all + in the expression:

+ is a character + to be + replaced

with this:
I hate the Plus sign!

Like this:


Code:


var strold = "+ is a character + to be + replaced";
var strnew = strold.replace(/\+/g,"I hate the Plus sign!");
WScript.Echo (strnew);


----------



## Mosaic1

If you want to do this over multiple lines of text, then you need to add the m switch too.


----------



## derektech

Thanks Mosaic1.
You're correct. I defined a new string object and remembered to escape the special characters such as ? and +.

It works perfectly.

thanks all for your input.


----------



## Mosaic1

Hi derektech,

You're welcome.

Mo


----------

