2014-10-09 76 views
1

我习惯在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的值,它就不再工作了。

回答

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>

+0

谢谢这工作!唯一的问题是它不会两次替换相同的值。例如,如果我有两次%title%,它只会取代第一个。 – 2014-10-09 08:42:27

+1

@SinanSamet在这种情况下,我们需要使用正则表达式 – 2014-10-09 08:43:27

+0

将它两次添加到查找数组也可以,我想我非常满意,非常感谢! – 2014-10-09 08:44:19