Reputation: 925
I have a string variable which could be something like:
var content = "blah blah [media:id=1] blah blah blah [media:id=0] blah blah";
And an array of Objects with Image information i.e.
var imageArray = [
{id:0, path:"/images/image.jpg"},
{id:1, path:"/images/anotherimage.jpg"}
]
I need a function to replace the "[media:id=x]" with the corresponding image object path from the imageArray via the id, so that my 'content' variable looks like:
"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 with this?
Upvotes: 4
Views: 524
Reputation: 14199
A simple array reduce could 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)
);
Upvotes: 0
Reputation: 3494
I'd do it like this:
I go through the array and check for each id if it exists in the string, if so I replace that part.
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);
Upvotes: 0
Reputation: 87233
You can use String#replace
to replace the id
s in the string by it's respective 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;
});
The regex \[media:id=(\d+)\]
will match
\[
: [
literalmedia:id=
literal(\d+)
: One or more number and put it into captured group\]
: ]
literalArray#find
can be used to find particular element in the array.
imageArray.find(o => o.id === Number(id))
will get the object whose id
matches the matched id from the string. If object is found in the array, the img
tag can be returned to replace it with the element else, complete string can be returned.
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);
Upvotes: 2