JS学习7-js正则表达式二 使用字符串的正则表达式方法

String对象中的正则表达式方法
方法含义
match(pattern)返回pattern中的子串或者null
replace(pattern, replacement)用replacement代替pattern
search(pattern)返回字符串中第一次出现pattern的位置
split(pattern)返回字符串按指定的pattern拆分的数组

 

1.使用match()方法获取匹配数组

var pattern = /box/ig;
var str ='This is a Box! That is a Box!';
alert(str.match(pattern));                  //返回box,box

2.使用search()来查找匹配数据

var pattern = /box/ig;
var str ='This is a Box! That is a Box!';
alert(str.search(pattern));              //返回10,从0开始数;同时search()本来就是全局查找,所以无需加“g”。

3.使用replace()来替换匹配到的数据

var pattern = /box/ig;
var str ='This is a Box! That is a Box!';
alert(str.replace(pattern,'AK-47'));  //返回This is a AK-47! That is a AK-47!

4.使用split()来拆分字符串成数组

var pattern = /box/ig;
var str ='This is a Box! That is a Box!';
alert(str.split('!'));     //返回This is a Box, That is a Box, 两个感叹号故拆分成长度为3的数组

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值