日期:2014-05-16 浏览次数:21546 次
var html = "<div>div and other content</div>"; var word = "div"; var replaceContent = "111"; var reg1 = new RegExp("([\\<][^\\<\\>]*)(" + word + ")([^\\>\\<]*[\\>])", "ig"); var str1 = html.replace(reg1, "$1{" + "$2" + "}$3"); alert(str1); var reg2 = new RegExp("(^|[^\\{]+)" + word + "([^\\{]+|$)", "ig"); var str2 = str1.replace(reg2, "$1" + replaceContent + "$2"); alert(str2); var reg3 = new RegExp("\\{" + word + "\\}", "ig"); var str3 = str2.replace(reg3, word); alert(str3);
------解决方案--------------------
替换了之后你要把值赋回去啊 要不怎么替换呢
[code=JScript]
//关键字高亮
function highLight(keyWords)
{
if(keyWords !=null)
{
var array = keyWords.substring(1,keyWords.length-1);
array = array.split( ", ");
var html = document.getElementById( "tds ").innerHTML;
for(var i=0;i <array.length;i++)
{
var oneKey = array[i];
var replaceContent = " <a style= 'color:red '> "+oneKey+ " </a> ";
var reg1 = new RegExp( "([\\ <][^\\ <\\> ]*)( " + oneKey + ")([^\\> \\ <]*[\\> ]) ", "ig ");
var str1 = html.replace(reg1, "$1{ " + "$2 " + "}$3 ");
var reg2 = new RegExp( "(^|[^\\{]+) " + oneKey + "([^\\{]+|$) ", "ig ");
var str2 = str1.replace(reg2, "$1 " + replaceContent + "$2 ");
var reg3 = new RegExp( "\\{ " + oneKey + "\\} ", "ig ");
html = str2.replace(reg3, oneKey);
}
document.getElementById( "tds ").innerHTML = html;
}
}
[/code]