js match方法的使用
阿新 • • 發佈:2020-07-04
match() 方法可在字串內檢索指定的值,或找到一個或多個正則表示式的匹配。
該方法類似 indexOf() 和 lastIndexOf(),但是它返回指定的值,而不是字串的位置。
語法
x1
stringObject.match(searchvalue)//searchvalue檢索的字串的值
2
stringObject.match(regexp)//regexp正則表示式
返回值
存放匹配結果的陣列。
檢索的兩種方式
-
字串
xxxxxxxxxx
5 1var str2=
2console.log(str2.match("World")); //["World", index: 6, input: "Hello World!,Hello World!", groups: undefined]
3console.log(str2.match("World").input); //Hello World!,Hello World!
4document.write(str2.match("World")); //World
5document.write(str2
-
正則表示式
x
1var str3="1 plus 2 equal 3"
2//用正則表示式匹配數字
3document.write(str3.match(/\d+/g)); //1,2,3
4console.log(str3.match(/\d+/g)); //["1", "2", "3"]