使用数组替换div中的占位符

时间:2014-10-09 08:34:26

标签: javascript jquery

我习惯在PHP中以这种方式接近它,所以我想知道是否有可能在Javascript中做到这一点。这就是我试过的:

$("#company-details").html(function () {
  var find = ['%title%', '%description%', '%photo%', '%website%', '%branch%', '%refnr%'];
  var replace = [value.title, value.description, value.photo, value.website, value.branch, value.refnr];
  return $(this).html().replace(find, replace); 
});

但是,只要我向任何数组添加超过1个值,它就不再起作用了。

1 个答案:

答案 0 :(得分:6)

我认为这不会起作用,你可能需要循环和替换

$("#company-details").html(function (i, html) {
    var find = ['%title%', '%description%', '%photo%', '%website%', '%branch%', '%refnr%'];
    var replace = [value.title, value.description, value.photo, value.website, value.branch, value.refnr];
    $.each(find, function (i, key) {
        html = html.replace(key, replace[i]);
    })
    return html;
});

我认为可以将其修剪为



if (!RegExp.escape) {
    RegExp.escape = function (s) {
        return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
    };
}


var value = {
    title: 'title',
    description: 'description',
    photo: 'photo',
    website: 'website',
    branch: 'branch',
    refnr: 'refnr',
};
$("#company-details").html(function (i, html) {
    var find = ['title', 'description', 'photo', 'website', 'branch', 'refnr'];
    $.each(find, function (i, key) {
        var regex = new RegExp('%' + RegExp.escape(key) + '%', 'g')
        html = html.replace(regex, value[key]);
    })
    return html;
});

#company-details {
    white-space: pre-line;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="company-details">
    Title: %title%
    Description: %description%
    Photo: %photo%
    Website: %website%
    Branch: %branch%
    Refnr: %refnr%
    Title2: %title%
</div>
&#13;
&#13;
&#13;