Find identifiers in a string and replace them with an array

I have a string variable that could be something like this:

var content = "blah blah [media:id=1] blah blah blah [media:id=0] blah blah";

And an array of objects with information about the image, i.e.

var imageArray = [
  {id:0, path:"/images/image.jpg"},
  {id:1, path:"/images/anotherimage.jpg"}
]

I need a function to replace "[media: id = x]" with the corresponding image object path from imageArray using id, so my content variable will look like this:

"blah blah <img src='/images/anotherimage.jpg' /> blah blah blah <img src='/images/image.jpg' /> blah blah";

But I'm not sure where to start?

+4
source share
3 answers

You can use String#replaceto replace idthe string with the corresponding image element.

content.replace(/\[media:id=(\d+)\]/g, function(m, id) {
    var path = imageArray.find(o => o.id === Number(id));
    if (path) {
        return `<img src="${path.path}" />`;
    }
    return m;
});

Regular expression \[media:id=(\d+)\]will match

  • \[: [literal
  • media:id= literal
  • (\d+): .
  • \]: ] literal

Array#find .

imageArray.find(o => o.id === Number(id))

, id . , img , else, .

var content = "blah blah [media:id=1] blah blah blah [media:id=0] blah blah";
var imageArray = [{
    id: 0,
    path: "/images/image.jpg"
}, {
    id: 1,
    path: "/images/anotherimage.jpg"
}];

var res = content.replace(/\[media:id=(\d+)\]/g, function(m, id) {
    var path = imageArray.find(o => o.id === Number(id));
    if (path) {
        return `<img src="${path.path}" />`;
    }
    return m;
});

console.log(res);
Hide result
+2

:
, , .

var content = "blah blah [media:id=1] blah blah blah [media:id=0] blah blah";

var imageArray = [
  {id:0, path:"/images/image.jpg"},
  {id:1, path:"/images/anotherimage.jpg"}
]

imageArray.forEach(function(element, i){
  var searchedStr= "[media:id="+element.id+"]";

  if(content.indexOf(searchedStr)!==-1)
    {
      var replaceStr = "<img src='"+element.path+"' />";
      content = content.replace(searchedStr,replaceStr);
    }
});
console.log(content);
Hide result
0

A simple array reduction can help you:

var content = "blah blah [media:id=1] blah blah blah [media:id=0] blah blah";
var imageArray = [
  {id:0, path:"/images/image.jpg"},
  {id:1, path:"/images/anotherimage.jpg"}
]

console.log(
  imageArray.reduce((res, obj) => {
    const 
      {id, path} = obj,
          
      re = new RegExp(`\\[media:id=${id}\\]`)
    ;

    return res.replace(re, `<img src="${path}" />`);
  }, content)
);
Run codeHide result
0
source

Source: https://habr.com/ru/post/1663586/


All Articles