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

Sin*_*met 1 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); 
});
Run Code Online (Sandbox Code Playgroud)

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

Aru*_*hny 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;
});
Run Code Online (Sandbox Code Playgroud)

我认为它可以修剪为

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;
});
Run Code Online (Sandbox Code Playgroud)
#company-details {
    white-space: pre-line;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)