在字符串中查找id并从数组中替换

时间:2016-12-13 06:29:49

标签: javascript regex

我有一个字符串变量,可能是这样的:

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"}
]

我需要一个函数来替换" [media:id = x]"使用imageArray中相应的图像对象路径通过id,以便我的内容'变量看起来像:

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

但我不知道从哪里开始呢?

3 个答案:

答案 0 :(得分:2)

您可以使用String#replace替换字符串中id的相应图像元素。

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;
});

正则表达式\[media:id=(\d+)\]将匹配

  1. \[[ literal
  2. media:id=字面意思
  3. (\d+):一个或多个号码并将其放入捕获的群组
  4. \]] literal
  5. Array#find可用于查找数组中的特定元素。

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

    将获取id与字符串中匹配的id匹配的对象。如果在数组中找到object,则可以返回img标记以将其替换为else else,可以返回完整的字符串。

    &#13;
    &#13;
    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);
    &#13;
    &#13;
    &#13;

答案 1 :(得分:0)

我这样做:
我遍历数组并检查每个id是否存在于字符串中,如果是,我将替换该部分。

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

简单的数组缩减可以帮助您:

&#13;
&#13;
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)
);
&#13;
&#13;
&#13;