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

Edited by Manixat
Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.