<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>javascript 替換有害字符(學(xué)習(xí)一下prototype與javascript正則)</title>
<script type="text/javascript">
/***********************************
/g是global全局替換,如果沒(méi)有這個(gè)標(biāo)識(shí),只替換第一處
/asdf/gi,i是忽略大小寫(xiě)。
還有個(gè)m不常用,是否換行匹配
***********************************/
String.prototype.htmlEncode = function(){
return this.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />");
};
function f(){
document.getElementById("div1").innerHTML="<00<0>".htmlEncode();//編碼之后
alert("<00<0>".htmlEncode());
document.getElementById("div2").innerHTML=document.getElementById("Text1").value.htmlEncode();//輸入<>/n之類(lèi)試試
alert(document.getElementById("Text1").value.htmlEncode());
}
</script>
</head>
<body>
<input id="Text1" type="text" value="<>\n" />
<div id="div1">hello</div>
<input type="button" value="ok" onclick="f();" />
<div id="div2">hi</div>
</body>
</html>