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"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With