<html>
<head>
<script type='text/javascript'>
function go(){
alert("getfile".replace(/(get)(.)(.*)/, function(_whole, _get, _char, _other) {
return "<font color='red'>" + _get + _char.toUpperCase() + _other + "</font>";
}));
}
</script>
</head>
<body onload='go()'>
test
</body>
</html>
上面的正則把getfile中f改變爲大寫。原來正則還可以這麼用。
下面的js是把原來的字符串中的一部分加上font標籤。匹配使用的關鍵字是key。
var html = $(this).html()
var reg = new RegExp(key, 'gi');
var oldKey = reg.exec(html)
html = html.replace(new RegExp(key, 'gi'),"<font color='red'>"+oldKey+"</font>"); // replace函數把前者替換爲後者
$(this).html(html);