6.0字符串方法的正则

一、上一节说了字符串的serch()方法
这里说一下字符串正则的其他方法
二、replace() 方法
用法1:str.replace(正则,新字符串)
用法1 字符串.replace(正则, function(‘匹配成功的字符’){})
规则:正则去匹配字符串,如果匹配成功,替换成新字符串,并且返回替换后的字符串,匹配失败 则原样返回
例如:

 var str = '2345678dfghjfghj'
        // var re = /j/
        // var newstr = str.replace(re, '卡卡')
        // console.log(newstr) //2345678dfgh卡卡fghj
 var str = '2345678dfghjfghj'
        var re = /j/g
        var newstr = str.replace(re, '卡卡')
        console.log(newstr) //2345678dfgh卡卡fgh卡卡
// 匹配失败
var re = /1/g
var newstr = str.replace(re, '卡卡')
console.log(newstr) //2345678dfghjfghj

三、函数式replace

// 函数式的replace
var str = 'ccccccc'
var re = /c/
var newstr = str.replace(re, function($0) {
    // 这个$0就是你匹配到的那个字符
    console.log($0) //c
    return ('----') //这个函数结果最终是一个字符串
})
console.log(newstr) //----cccccc
// 敏感词过滤
var str = '云想衣裳花想容,春风拂槛露华浓'
var re = /||/g
var newstr = str.replace(re, function($0, $1, $2) {
    return ''
})
console.log(newstr) //想裳想容,春风拂槛露华浓

四、方法三 str.split(正则,返回的数组的长度)

// 匹配成功返回数组
var str = '2019-1-1 12:12:12'
var re = /-|\s|:/g
var newstr = str.split(re)
console.log(newstr) //["2019", "1", "1", "12", "12", "12"]

var newstr = str.split(re, 3)
console.log(newstr) //["2019", "1", "1"]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值