views:

93

answers:

5

Hi,

What would be a good way to do this. I have a string with lots of "&lt;" and &gt; and I want to replace them with < and >. So i wrote this:

var str = &lt;/text&gt;&lt;word34212&gt;
var p = str.replace('\&lt\;','\<');
var m = p.replace('\&gt\;','\>');

but that's just doing the first instance of each - and subsequent instances of &lt;/&gt; are not replaced. I considered first counting the instances of the &lt; and then looping and replacing one instance of the code on every iteration...and then doing the same for the &gt; but obviously this is quite long-winded.

Can anyone suggest a neater way to do this?

+4  A: 

Taken from: http://www.bradino.com/javascript/string-replace/

The JavaScript function for String Replace replaces the first occurrence in the string. The function is similar to the php function str_replace and takes two simple parameters. The first parameter is the pattern to find and the second parameter is the string to replace the pattern with when found. The javascript function does not Replace All...

To ReplaceAll you have to do it a little differently. To replace all occurrences in the string, use the g modifier like this:

str = str.replace(/find/g,”replace”)
NinjaCat
Brilliant thanks all. I did google this! Must learn REGEX properly.
elduderino
A: 

I thing a associative array [regex -> replacement] and one iteration would do it

Julio Faerman
+5  A: 

To replace multiple occurances you use a regular expression, so that you can specify the global (g) flag:

var m = str.replace(/&lt;/g,'<').replace(/&gt;/g,'>');
Guffa
+2  A: 

You need to use the global modifier:

var p = str.replace(/\&lt\;/g,'\<');
JacobM
+2  A: 

You need to use de /g modifier in your regex and it'll work. Check this page for an example : http://www.w3schools.com/jsref/jsref_replace.asp

Gabriel