我一直在寻找一百万份表格,并尝试了所有表格。我需要用值替换文本的所有实例
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
,因此这两种方式均无效。