Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through Javascript regex matches to modify original string

Just wondering the best way to replace in place matches on a string.

value.replace("bob", "fred");

for example, works, but I want each instance of "bob" to be replaced with a random string I have stored in an array. Just doing a regex match returns me the matching text, but doesn't allow me to replace it in the original string. Is there a simple way to do this?

For example I would expect the string:

"Bob went to the market. Bob went to the fair. Bob went home"

To maybe pop out as

"Fred went to the market. John went to the fair. Alex went home"
like image 354
Grazfather Avatar asked Oct 07 '22 13:10

Grazfather


1 Answers

You can replace with the value of a function call:

var names = ["Fred", "John", "Alex"];
var s = "Bob went to the market. Bob went to the fair. Bob went home";
s = s.replace(/Bob/g, function(m) {
    return names[Math.floor(Math.random() * names.length)];
});

This gives for example:

"John went to the market. Fred went to the fair. John went home"
like image 91
Mark Byers Avatar answered Oct 13 '22 11:10

Mark Byers