嗯,瞭解了,以固定的字串取代為另一個字串,大致是這樣吧?我寫了一個簡單的程式如下:
代碼:
<script>
var keywords = Array(
Array("Google AdSense", "http://ads.google.com/"),
Array("clicking", "http://click.to/"),
Array("advertisers", "http://advertisers.com/")
)
function replaceKeyword(objID) {
var text = "";
if (objID != null) {
text = document.getElementById(objID).outerHTML;
} else {
text = document.body.innerHTML;
}
for (var i = 0; i < keywords.length; i++) {
var re = new RegExp(keywords[i][0].replace(/\s+/, "\\s+"), "g");
var m = re.exec(text);
if (m != null) {
for (var j = 0; j < m.length; j++) {
var reg = new RegExp(m[j], "g");
text = text.replace(reg, "<a href='" + keywords[i][1] + "'>" + m[j] + "</a>");
}
}
}
if (objID != null) {
document.getElementById(objID).outerHTML = text;
} else {
document.body.innerHTML = text;
}
}
</script>
使用時,在 <body> 內加一段語法來執行
代碼:
<body onload="replaceKeyword('websiteContent')">
帶入的參數可以沒有,或是帶入某個元素的 ID。
程式最上面的地方可以設定關鍵字及要填入的網址,如果關鍵字內有空白,我在搜尋時會用 \s+ 取代,\s+ 表示一個以上的空白、跳行、定位等等...這樣遇到斷行的關鍵字時才能有效判斷,完整的網頁範例,看原始碼可知道效果:
http://65.98.116.226/~wmh/