test,exec,match,replace方法区别 正则

这四种方法都是用来检测字符串是否包含某一子串或是否匹配否个正则表达式

test方法,匹配返回true,不匹配返回false

match,匹配返回匹配到的数组(包含多次/g),匹配一次返回包含匹配子串的数组,具体看下面例子,没有匹配到返回null

replace,查找替换,两个参数,第一个参数查找的内容,可以是字符串或正则表达式,第二个参数(字符串,$1...$10,函数),用第二个参数替换第一个参数

exec,匹配返回匹配值,不匹配返回null

var str='aa-bb-cc'
var reg=/\w{2}/g
var reg2=/\w{3}/g

reg.test(str)  //true
reg2.test(str) //false

str.match(reg) // (3) ["aa", "bb", "cc"]
str.match(/\w{2}/) //["aa", index: 0, input: "aa-bb-cc", groups: undefined] 一次匹配
str.match(reg2) //null

reg.exec(str) //["aa", index: 0, input: "aa-bb-cc", groups: undefined]
reg2.exec(str) //null

// 用replace实现首字母大写
str.replace(/(^\w|\-\w)/g,function($1){return $1.toUpperCase()}) //"Aa-Bb-Cc"

一定要亲自试验一下  可以很快理解

猜你喜欢

转载自www.cnblogs.com/bais/p/9168988.html