js变量模板-replace用法

<script type="text/javascript">

var _tplshowHtml = '<div class="modal fade" id="{Id}">' +

'<div class="modal-header">' +

'<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>' +

'<h5 class="modal-title">{Title}</h5>' +

'</div>' +

'<div class="modal-body " >' +

'<div class="row" id = "bodyContext" ></div>'+

'</div>' +

'<div class="modal-footer" >' +

'<button type="button" class="btn btn-primary ok" data-dismiss="modal" onclick="avdSearchSubmit()">{BtnOk}</button>' +

'<button type="button" class="btn btn-default cancel" data-dismiss="modal">{BtnCancel}</button>' +

'</div>' +

'</div>';

var html = _tplshowHtml.replace(/\{(\w+)\}/igm, function(node, key,index) {

console.log(node+":"+key,index);

return {

Id : "modalId",

Title : "ops.title",

Url : "ops.url",

Height : "ops.height",

BtnOk : "ops.btnok",

BtnCancel : "ops.btncl",

width : "ops.width"

}[key];

});

alert(html);

</script>

<button id="button1">弹出普通replace结果</button>

<button id="button2">弹出含回调replace结果</button>

<script type="text/javascript">

document.getElementById("button1").onclick = function() {

    alert('10 13 21 48 52'.replace(/\d+/g, '*')); //用 * 替换所有的数字

};

document.getElementById("button2").onclick = function() {

    alert('10 13 21 48 52'.replace(/\d+/g, function(match,x) {

    alert(x);

        return parseInt(match) < 30 ? '*' : match;

    }));

};

</script>

<script type="text/javascript">

name = "Doe, John, John";

var name1=name.replace(/(\w+)\s*, \s*(\w+), \s*(\w+)/,"$3 $1 $2");

alert(name1);

</script>

评论

© 锋镝 | Powered by LOFTER