js match方法的使用


 

match() 方法可在字符串內檢索指定的值,或找到一個或多個正則表達式的匹配。

該方法類似 indexOf() 和 lastIndexOf(),但是它返回指定的值,而不是字符串的位置。

語法

 
 
 
x
 
 
 
 
1
stringObject.match(searchvalue)//searchvalue檢索的字符串的值
2
stringObject.match(regexp)//regexp正則表達式
 
 

返回值

存放匹配結果的數組。

檢索的兩種方式

  1. 字符串

     
     
     
    xxxxxxxxxx
    5
     
     
     
     
    1
    var str2="Hello World!,Hello World!";
    2
        console.log(str2.match("World"));   //["World", index: 6, input: "Hello World!,Hello World!", groups: undefined]
    3
        console.log(str2.match("World").input); //Hello World!,Hello World!
    4
        document.write(str2.match("World"));    //World
    5
        document.write(str2.match("world")) //null
     
     
  2. 正則表達式

     
     
     
    x
     
     
     
     
    1
    var str3="1 plus 2 equal 3"
    2
        //用正則表達式匹配數字
    3
        document.write(str3.match(/\d+/g)); //1,2,3
    4
        console.log(str3.match(/\d+/g));    //["1", "2", "3"]
     
     

     


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM