replace()最js中比較簡單的字符替換函數(shù),但是它也是可以跟正則結(jié)合實現(xiàn)強大的字符替換效果。
示例代碼如下:
<script language="javascript">
var strM = "javascript is a good script language";
//在此我想將字母a替換成字母A
alert(strM.replace("a","A"));
</script>
它只替換了首字母。但如果加上正則表達式結(jié)果就不一樣了!replace()支持正則表達式,它可以按照正則表達式的規(guī)則匹配字符或字符串,然后給予替換!
<script language="javascript">
var strM = "javascript is a good script language";
//在此我想將字母a替換成字母A
alert(strM.replace(/a/,"A"));
</script>
<script language="javascript">
var strM = "javascript is a good script language";
//在此將字母a全部替換成字母A
alert(strM.replace(/a/g,"A"));
</script>
由上可知,當正則表達式有"g"標志時,代表將處理整個字符串。
<script language="javascript">
var strM = "javascript is a good script language";
alert(strM.replace(/(javascript)\s*(is)/g,"$1 $2 fun. it $2"));
</script>
先看看簡單例子:將所有單詞首字母換成大寫。
<script language="javascript">
var strM = "javascript is a good script language";
function change(word)
{
return word.indexOf(0).toUpperCase()+word.substring(1);
}
alert(strM.replace(/\b\w+\b/g,change));
</script>
由上可知,當正則表達式有"g"標志時,代表將處理整個字符串,即函數(shù)change的變換將應(yīng)用于所有匹配的對象。而該函數(shù)有三個或更多參數(shù),具體個數(shù)視正則表達式而定。
<script language="javascript">
var strM = "javascript is a good script language";
function change(word)
{
var result = word.match(/(\w)/g);
if ( result )
{
var str = "";
for ( var i=result.length-1; i>=0; i-- )
{
str += result;
}
return str;
}
else
{
return "null";
}
}
alert(strM.replace(/\b(\w)+\b/g,change));
</script>
更多建議: