Saturday, May 9, 2009

Replacing characters within strings with Javascript

I found out today how to replace characters within a string using Javascript.

It's not hard.

First, you take the string that has characters that need replacing.

You make a regular expression of the characters that need replacing. -> this uses the javascript RegEx("string") function.

You make a variable to hold the new string that is generated from the replacing.

You have a new string with replaced characters.

In the following example, I wanted to replace a string with the empty string, removing the unwanted characters.



temp will have the value of  "1,,3,4".

If you want to take the comma out, also, just put "2," into the regular expression function.

The regular expression function generates a regular expression that is understandable to javascript.  The first code would generate /2/ while the second code would generate /2,/.

Hope this helps.

No comments:

Post a Comment