Javascript Regular Expressions

fender

Limp Gawd
Joined
Mar 2, 2003
Messages
417
How would you perform this PHP regular expression replacement

PHP:
preg_replace('/start(.*?)end/', 'begin"$1"finish', $source);

with javascript?

Code:
source.replace(/start(.*?)end/g,'begin' + ??? + 'finish');
 
OK I just tried doing it the same way and it looks to be working.

Code:
source.replace(/start(.*?)end/g,"begin$1finish");

...in case anyone was wondering.
 
OK, what if I have a string such as this

Code:
var string = '<9x>This</9x> is some text that I <0q>want</0q> to show.'

I want to replace all instances of <9x></9x> with (9x)(/9x) and <0q></0q> with (0q)(/0q). I don't know what tags the string will contain so I have an array with all the possible options.

Code:
var choices = new Array();
choices[0] = /<0q>(.*?)<\/0q>/;
choices[1] = /<h3>(.*?)<\/h3>/;
choices[2] = /<9x>(.*?)<\/9x>/;

And an array with the replacements.

Code:
var replacements = new Array();
replacements [0] = /(0q)$1(\/0q)/;
replacements [1] = /(h3)$1(\/h3)/;
replacements [2] = /(9x)$1(\/9x)/;

If I had something similar in PHP, the PHP equivalent of something like this

Code:
text.replace(choices,replacements);

would get the job done, but apparently in javascript arrays can't be used in this situation. So how could I get what I want done?

None: disregard the fact that I didn't escape the parentheses in the replacements array.
 
Try something like:

PHP:
<?PHP str_replace($compare_to,$replace_with,$searchstr); ?>
 
Yes, I know how to do it in PHP, but I need to do this with javascript. And as far as I know, you need either ereg_replace or preg_replace if you want to use regular expressions and not str_replace.
 
Back
Top