javascript的replace方法的用法

來源:互聯網
上載者:User

replace是String對象上的一個方法,可以實現把字串中某些指定的子字串替換成其他字串。用法為 “字串.replace(parm1,parm2)”。其中parm1的老字串,可以使一般字元串,也可以是一個Regex;parm2退換的結果,可以是一個字串,更重要的是也可以是一個javascript的方法,作為回呼函數。下面用幾個小例子來分別說明一下。

 代碼如下 複製代碼

alert('abcabd'.replace('ab','12'));

這裡alert的結果就是12cabd,注意到它只替換到第一次出現的,後面不做替換。如果把子串全部替換,只能用Regex的方法來操作。

 代碼如下 複製代碼

alert('abcabdAbe'.replace(/ab/g,'12'));

這樣得到的結果為12c12dAbe,g 表示進行全域替換,同時也可以用 i 來忽略大小寫,注意Regex不能用引號引起來。

 代碼如下 複製代碼

var i = 0;
alert('abAabBabC'.replace(/ab/g, function(m) {
i++;
return m + '-' + i + '-';
}));

這裡的結果是ab-1-Aab-2-Bab-3-C,當匹配到子字串時,調用回調方法,並把匹配到的值作為參數傳入。另外一個例子,把字串中小於30的數替換成星號

 代碼如下 複製代碼

alert('10 33 21 18 52'.replace(/d+/g, function(match) {
return parseInt(match) < 30 ? '*' : match;
}));


下文展示了幾種javascript正則表示式的repalce方式,有些方式我們很少在別的地方看到,如第二種和第三方中方法。

 代碼如下 複製代碼

//下面的例子用來擷取url的兩個參數,並返回urlRewrite之前的真實Url
var reg=new RegExp("()(\d+),(\d+).aspx","gmi");
var url="1017141,20361055.aspx";

//方式一,最簡單常用的方式
var rep=url.replace(reg,"$1ShowBook.aspx?bookId=$2&chapterId=$3");
alert(rep);

//方式二 ,採用固定參數的回呼函數
var rep2=url.replace(reg,function(m,p1,p2,p3){return p1+"ShowBook.aspx?bookId="+p3+"&chapterId="+p3});
alert(rep2);

//方式三,採用非固定參數的回呼函數
var rep3=url.replace(reg,function(){var args=arguments; return args[1]+"ShowBook.aspx?bookId="+args[2]+"&chapterId="+args[3];});
alert(rep3);


//方法四
//方式四和方法三很類似, 除了返回替換後的字串外,還可以單獨擷取參數
var bookId;
var chapterId;
function capText()
{
    var args=arguments;
    bookId=args[2];
    chapterId=args[3];
    return args[1]+"ShowBook.aspx?bookId="+args[2]+"&chapterId="+args[3];
}

var rep4=url.replace(reg,capText);
alert(rep4);
alert(bookId);
alert(chapterId);


//除了使用replace方法擷取正則表示式的分組外,還可以使用test ,exec方法擷取分組,只是手法有所不同而已
var reg2=new RegExp("()(\d+),(\d+).aspx","gmi");
var m=reg2.exec("1017141,20361055.aspx");
var s="";
//擷取所有的分組
for (i = 0; i < m.length; i++) {
      s = s + m[i] + "n";     
      }
alert(s);

bookId=m[2];
chapterId=m[3];
alert(bookId);
alert(chapterId);


//使用test方法擷取分組
var reg3=new RegExp("()(\d+),(\d+).aspx","gmi");
reg3.test("1017141,20361055.aspx");
//擷取三個分組
alert(RegExp.$1);
alert(RegExp.$2);
alert(RegExp.$3);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.