簡體   English   中英

JavaScript替換所有奇怪的行為

[英]JavaScript Replace all odd behavior

我想要這個代碼:

function renderTemplate(temp,content){ 
    for (var i in temp){
        replace = new RegExp("["+i+"]",'g');
        content = content.replace(i,temp[i]);
    }
    return content;
}
var temp = {'status':'ok','id':150};
var content = "your status is [status], again! your status is [status], and your id is [id], yes[id]";

alert(renderTemplate(temp,content));

為我生成這個字符串:

your status is ok, again! your status is ok, and your id is 150, yes 150

相反,我得到:

your ok is [status], again! your status is [status], and your 150 is [id], yes[id]

看看ok地方....

你可以在這里運行它: http//jsfiddle.net/v9vzd/

謝謝

請嘗試以下代碼:

function renderTemplate(temp,content){ 
    for (var i in temp){
        replace = new RegExp("\\["+i+"\\]",'g');
        content = content.replace(replace,temp[i]);
    }
    return content;
}
var temp = {'status':'ok','id':150};
var content = "your status is [status], again! your status is [status], and your id is [id], yes[id]";

alert(renderTemplate(temp,content));

您沒有使用您創建的RegExp對象。 方括號創建一個字符類,所以oyu必須轉義方括號(在RegExp構造函數調用中,你必須轉義轉義反斜杠,所以它是兩個反斜杠)。

盡管阿德里安·朗(Adrian Lang)的答案很好,但我認為你並沒有采取最好的方法。 在轉義時編譯變量的正則表達式可能很尷尬,而且性能通常較慢。

如果是我,我會利用傳遞函數來replace()

function renderTemplate(temp, content) {
    return content.replace(/\[([^[\]+)\]/g, function ($0, key) {
        return temp[key];
    });
}

工作演示: http//jsfiddle.net/AKsHb/

這是有效的,因為子表達式捕獲, ([^\\]]+)作為第二個參數傳遞給替換函數 - 在上面的函數中標記為key - 這匹配文字[]之間的任何內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM