Shahariar Rahman Sajib
Shahariar Rahman Sajib

Reputation: 157

How to replace using regex?

var result = [{"figure figure watch?v="}, {"figure data watch?v="}]
console.log(result.replace(res=> res.('figure', 'ifigure', 'watch?v=' , 'embeded/')))

I want result = [{"ifigure ifigure embeded/"}, {"ifigure data embeded/"}]

Can you help?

Upvotes: 0

Views: 73

Answers (2)

Ali Hassan
Ali Hassan

Reputation: 86

First of all [{"ifigure ifigure embeded/"}, {"ifigure data embeded/"}] you have a syntax error here. you cannot enclose string in an object. you will need to do something like this. if in future you want to replace new string, just add them in this object.

var mapObj = {
   'watch?v=':"embeded/",
   'figure':"ifigure"
};

var result = ["figure figure watch?v=", "figure data watch?v="];
console.log(result.map(res=> res.replace(/watch\?v=|figure/gi, function(matched){
  return mapObj[matched];
})));

Upvotes: 1

Shubham P
Shubham P

Reputation: 1282

The simplest way will be to use Array.map method with regex -

var result = ["figure figure watch?v=", "figure data watch?v="];
result.map(e => e.replace(/watch\?v=/g, "embeded/").replace(/figure/g, "ifigure"));
// (2) ["ifigure ifigure embeded/", "ifigure data embeded/"]

Check out this question for more on replacing with Regex Fastest method to replace all instances of a character in a string

Upvotes: 1

Related Questions