Jump to content

Javascript Regex Multiple Strings Replace?


Manixat

Recommended Posts

Heya, is there a way to find different strings in a text and replace them depending on the found string using a single replace methog ?

 

I believe my explanation is worse than bad so I guess I have to give an example:

 

if I have this sentence "Scott is Bob's best friend and Tod's worst enemy"

 

if I want to replace scott with greg, bob with jeremy and tod with simon I can do this

 

text.replace(/scott/,'Greg').replace(/bob/,'Jeremy').replace(/tod/,'Simon');

 

but my question is if I can do something like this

 

text.replace(/scott|bob|tod/,/greg|jeremy|simon/)

 

Is it possible?

 

EDIT: I know in this case I don't have to use regular expressions, but this is just an example, in my real code I have to use regex

You could create a function that will do it from an array for strings found/replaced. Then like using preg_replace with an array in PHP, you would put the regex for each of the first array, and then the replacement in the second.

You could create a function that will do it from an array for strings found/replaced. Then like using preg_replace with an array in PHP, you would put the regex for each of the first array, and then the replacement in the second.

 

Yes, I know I can do that, but my page is running in background so my goal is to use as less CPU as I can that's why I wanna avoid doing loops and using 10+ replace methods

Yes, I know I can do that, but my page is running in background so my goal is to use as less CPU as I can that's why I wanna avoid doing loops and using 10+ replace methods

 

Even if there was a built in function that allowed you to pass arrays, such as preg_replace allows in HP, how do you think that function would actually perform the logic? it would use loops.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.