定義和用法
replace() 方法用於在字串中用一些字元替換另一些字元,或替換一個與Regex匹配的子串。
文法
stringObject.replace(regexp/substr,replacement)參數 描述
regexp/substr 必需。規定子字串或要替換的模式的 RegExp 對象。
請注意,如果該值是一個字串,則將它作為要檢索的直接量文字模式,而不是首先被轉換為 RegExp 對象。
replacement 必需。一個字串值。規定了替換文本或產生替換文本的函數。
傳回值
一個新的字串,是用 replacement 替換了 regexp 的第一次匹配或所有匹配之後得到的。
樣本
下面的樣本示範了 replace 方法將第一次出現的單詞 "The" 替換為單詞 "A" 的用法。
| 代碼如下 |
複製代碼 |
function ReplaceDemo(){ var r, re; // 聲明變數。 var ss = "The man hit the ball with the bat.n"; ss += "while the fielder caught the ball with the glove."; re = /The/g; // 建立Regex模式。 r = ss.replace(re, "A"); // 用 "A" 替換 "The"。 return(r); // 返回替換後的字串。 } |
更多詳細內容請查看:http://www.111cn.net/wy/99/js_replace_replaceall.htm
上面的只能替換一次,下面我們來看看實現多次替換的方法
| 代碼如下 |
複製代碼 |
<script language="javascript"> $(function(){ var str = 'rtsp://112.5.172.36:10082/1d8a097f_51bf_4ef2_8380_71d63e9fb97a/c1v1.3gp'; var re = /://.*$/i; if(re.test(str)){ var newStr = str.substring(str.indexOf("://")+3, str.length); var strarray = newStr.split("/"); alert(strarray[0].substring(0, strarray[0].indexOf(":"))); alert(replaceStr(strarray[1])); } function replaceStr(str){ var newstring = str; while(newstring.indexOf("_") > 0) { newstring = newstring.replace("_","-"); } return newstring; } }); </script> |