1. 程式人生 > >js入門5-字符的查詢與過濾 加上使用正則表達式

js入門5-字符的查詢與過濾 加上使用正則表達式

表達 indexof arch document string對象 查找 reg 則表達式 fun

<h2>5.String對象:字符的查找與過濾</h2>
<input type="text" id="txtString"/><br/>
<input type="button" value="過濾特殊字符(js)" onclick="searchStringAndReplace();"/>
//查找並替換文本框中錄入的自字符串js為*
function searchStringAndReplace(){
var str = document.getElementById("txtString").value;
var index = str.indexOf("js",0);
while(index>-1){
str = str.replace("js","*");
index = str.indexOf("js",index+1);
}
document.getElementById("txtString").value = str;
}

技術分享

<input type="button" value="查找字符並過濾(使用正則表達式)" onclick="stringByRegex();"/>
//使用正則表達式操作文本
function stringByRegex(){
var str = document.getElementById("txtString").value;
var result = str.match(/js/gi);
document.getElementById("txtString").value = str.replace(/js/gi,"*");
alert("共替換了"+result.length+"處");
}

技術分享

js入門5-字符的查詢與過濾 加上使用正則表達式