簡體   English   中英

用javascript替換雙卷曲大括號

[英]Replacing Double Curly Braces with javascript

我試圖將String對象原型化為一個replaceWith函數,使我能夠直接替換而不使用正則表達式

String.prototype.replaceWith = function(f, t) {
    var regExp = new RegExp("[" + f + "]", "g");
    return this.replace(regExp, t);
};

當我在這個字符串{{Hello}}中測試我的代碼時,我發現替換雙花括號是個問題

測試

'{{Hello}}'.replaceWith('{{','<<').replaceWith('}}','>>');

結果是

 "<<<<Hello>>>>"

什么時候應該

"<<Hello>>"

我的劇本出了什么問題?

謝謝你的幫助

[{{][{]完全相同,只與{ in regex相同。 方括號表示與該類中任何一個字符匹配的字符類。 你應該改變:

"[" + f + "]"

至:

f

所以你有了:

String.prototype.replaceWith = function(f, t) {
    var regExp = new RegExp(f, "g");
    return this.replace(regExp, t);
};

正如Marlin指出的那樣具有與String.prototype.replace相同的功能,除了你不需要添加g修飾符,並且在我的腦海中'{{Hello}}'.replace(/{{/g, '<<'); 除了'{{Hello}}'.replaceWith('{{', '<<');之外,對其他程序員來說更簡潔易懂'{{Hello}}'.replaceWith('{{', '<<');

@PaulPRO是正確的,但在chrome中你可以使用replace:

"{{hello}}".replace("}}",">>").replace("{{","<<")

哪個回報

"<<hello>>"

您使用的是什么環境?

暫無
暫無

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

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