本文實(shí)例講述了JavaScript使用replace函數(shù)替換字符串的方法。分享給大家供大家參考。具體如下:

成都創(chuàng)新互聯(lián)公司2013年開(kāi)創(chuàng)至今,先為民勤等服務(wù)建站,民勤等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為民勤企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問(wèn)題。
JavaScript通過(guò)replace函數(shù)替換字符串,下面的代碼將Visit
Microsoft中的MicroSoft替換成jb51.net
!DOCTYPE
html
html
body
p
Click
the
button
to
replace
"Microsoft"
with
"jb51.net"
in
the
paragraph
below:
/p
p
id="demo"Visit
Microsoft!/p
button
onclick="myFunction()"Try
it/button
script
function
myFunction()
{
var
str=document.getElementById("demo").innerHTML;
var
n=str.replace("Microsoft","jb51.net");
document.getElementById("demo").innerHTML=n;
}
/script
/body
/html
希望本文所述對(duì)大家的javascript程序設(shè)計(jì)有所幫助。
1、定義一個(gè)含方括號(hào)"[]"的字符串
var?str?=?"adadsd[ads]ad";
2、通過(guò)replace進(jìn)行括號(hào)替換
str.replace('[','').replace(']','');//括號(hào)替換為空
replace(substr,replacement) 方法執(zhí)行的是查找并替換的操作。
查找與 substr 相匹配的子字符串,然后用 replacement 來(lái)替換這些子串
1.首先將它們拼成字符串 s 2.s=s.replace(/xml|\/xml|record|\/record/g,""); 3.alert(s) === script var s="xml" +"recordAISHUMIN,female,1976-08-06/record" +"recordANHONG,male,1976-09-06/record" +"recordANXIAOZHONG,female,1977-09-17/record" +"recordBAINING,female,1979-05-10/record" +"recordDONGDAIYU,male,1976-04-03/record" +"recordDONGZHAOQIANG,male,1978-07-22/record" +"recordFANGXIUZE,male,1972-04-11/record" +"recordFUSONGQIANG,male,1982-04-11/record" +"/xml" s=s.replace(/xml|\/xml|record|\/record/g,""); alert(s) /script
步驟:
1、 通過(guò)正則表達(dá)式,實(shí)現(xiàn)replaceAll的功能
2、通過(guò)body.innerHTML獲取網(wǎng)頁(yè)信息
3、替換body中的內(nèi)容,再賦值給body
示例:
body
p測(cè)試/p
/body
script?type="text/javascript"
String.prototype.replaceAll?=?function(reallyDo,?replaceWith,?ignoreCase)?{
//自定義replaceAll方法,reallyDo:被搜索的子字符串。replaceWith:用于替換的子字符串
if?(!RegExp.prototype.isPrototypeOf(reallyDo))?{
return?this.replace(new?RegExp(reallyDo,?(ignoreCase???"gi":?"g")),?replaceWith);
}?else?{
return?this.replace(reallyDo,?replaceWith);
}
}
/script
script
var?bd?=?document.getElementsByTagName('body')[0];//獲取body節(jié)點(diǎn)
var?s?=?new?String(bd.innerHTML);//獲取body的html信息
var?a?=?s.replaceAll('p','div');//把節(jié)點(diǎn)p替換成div
delete?s;//釋放變量s
bd.innerHTML?=?a;//更新body的html信息
delete?a;//釋放變量a
/script
本文標(biāo)題:javascript替換,javascript替換文字
分享鏈接:http://chinadenli.net/article40/dsejeeo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開(kāi)發(fā)、標(biāo)簽優(yōu)化、Google、企業(yè)建站、自適應(yīng)網(wǎng)站、外貿(mào)網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)