簡體   English   中英

.replace()所有帶有Regex的實例不起作用

[英].replace() all instances with Regex not working

我一直在尋找一百萬份表格,並嘗試了所有表格。 我需要將所有文本實例替換為值

this.text = {
    title:'This is my Title',
};

this.replaceTags = function() {
    //Replace Text
    $.each(this.text, function( index, value ){
        var item = "{{$text:"+index+"}}";
        var bodyText = $('body').html();
        var regex = new RegExp(item, 'g');
        var newText = bodyText.replace(regex,value);
        $('body').html(newText);
    })
}

我也嘗試過

this.text = {
    title:'This is my Title',
};

this.replaceTags = function() {
    //Replace Text
    $.each(this.text, function( index, value ){
        var item = "{{$text:"+index+"}}";
        var bodyText = $('body').html();
        var newText = bodyText.replace(/item/g,value);
        $('body').html(newText);
    })
}

但是都沒有用。 我的語法是否錯誤?

由於$是正則表達式中的特殊字符(與行的末尾匹配),因此必須使用\\對其進行轉義。 由於\\是字符串中的特殊字符(它是轉義字符),因此您必須自行轉義。 因此,您的代碼變為:

var item = "{{\\$text:"+index+"}}";
var bodyText = $('body').html();
var regex = new RegExp(item, 'g');
var newText = bodyText.replace(regex,value);
$('body').html(newText);

演示


bodyText.replace(/item/g,value)會從字面上查找字符序列item ,因此無論哪種方式都不會起作用。

暫無
暫無

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

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