我一直在搜索,我从堆栈溢出中发现了这个Question 所以我一直试图让它与我的代码一起工作,我似乎无法让它工作。
html = '<li style="list-style:none;">';
cmnt = this.comment.replace(new RegExp( "(" + preg_quote( firsttext ) + ")" , 'gi' ), "<span class='cutecl'>$1</span>");
cmnt = cmnt.replace(new RegExp( "(" + preg_quote( secondtext ) + ")" , 'gi' ), "<span class='wincl'>$1</span>");
cmnt = cmnt.replace(new RegExp( "(" + preg_quote( thirdtext ) + ")" , 'gi' ), "<span class='failcl'>$1</span>");
html += cmnt;
html += '<br/><a href="http://www.youtube.com/userPage.php?author='+escape(this.author)+'">'+this.author+'</a>';
html += '<span class="label"> - '+(this.published.getMonth() + 1)+'/'+this.published.getDate()+'/'+this.published.getFullYear()+'</span>';
html += '</li>';
$('#comment').append(html);
当然:
function preg_quote( str ) {
return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
}
当我有
时 cmnt = this.comment.replace(new RegExp( "(" + preg_quote( firsttext ) + ")" , 'gi' ), "<span class='cutecl'>$1</span>");
cmnt = cmnt.replace(new RegExp( "(" + preg_quote( secondtext ) + ")" , 'gi' ), "<span class='wincl'>$1</span>");
cmnt = cmnt.replace(new RegExp( "(" + preg_quote( thirdtext ) + ")" , 'gi' ), "<span class='failcl'>$1</span>");
包含在我的代码中,当我想要它创建那个li时没有出现,但如果它消失了,它运行正常,任何线索我做错了什么?感谢提前,阿里
以下是问题的解答:http://jsfiddle.net/Yg8Qe/2/
答案 0 :(得分:1)
从OP获得更多信息之后,这是修复:不要在替换字符串中对$1
进行硬编码。
function preg_quote(str) {
return (str + '').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
}
function wrap(data, search, before, after) {
return data.replace( new RegExp( preg_quote( search ), 'gi' ), before + search + after );
}
var var1 = "var1",
var2 = "var2",
var3 = "var3",
cmnt = "this comment will be replaced with var1 var2 var3";
cmnt = wrap(cmnt, 'var1', '<span class="cutecl">', '</span>');
cmnt = wrap(cmnt, 'var2', '<span class="wincl">', '</span>');
cmnt = wrap(cmnt, 'var3', '<span class="failcl">', '</span>');
$('#comment').append('<li style="list-style:none;">' + cmnt + '</li>');
这里有很多代码清理:缩进,分号,消除不必要的变量,并将“换行”逻辑放入一个漂亮的,可重用的函数中。
的 Demo → 强> 的
看起来您在代码的第一行中遗漏了 cmnt = this.comment.
“无法正常工作。”
// ↓↓↓ right here
cmnt = this.comment.replace(new RegExp( "(" + preg_quote( firsttext ) + ")" , 'gi' ), "<span class='cutecl'>$1</span>");
cmnt = cmnt.replace(new RegExp( "(" + preg_quote( secondtext ) + ")" , 'gi' ), "<span class='wincl'>$1</span>");
cmnt = cmnt.replace(new RegExp( "(" + preg_quote( thirdtext ) + ")" , 'gi' ), "<span class='failcl'>$1</span>");