gpt4 book ai didi

javascript - .replace() 所有正则表达式不起作用的实例

转载 作者:行者123 更新时间:2023-12-02 17:18:01 25 4
gpt4 key购买 nike

我已经查看了一百万份表格并尝试了所有表格。我需要用该值替换文本的所有实例

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);

DEMO

<小时/>

bodyText.replace(/item/g,value) 会逐字查找字符序列 item,因此无论哪种方式都不起作用。

关于javascript - .replace() 所有正则表达式不起作用的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24232236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com