JavaScript正则表达式

字符串的正则表达式

2018-08-01  本文已影响1人  椰果粒

str.search():返回第一个匹配的子串的位置,不支持全局
str.replace(reg,function(){}):匹配并替换
str.match(reg):将所有的匹配结果放到一个数组中
str.split(reg):按照正则匹配到的内容切割

举个栗子🌰

var reg = /\d{2}/g;
var str = "ab3f12fa34";
console.log(str.search(reg));   // 4
var reg = /\d{2}/g;
var str = "ab3f12fa34";
console.log(str.replace(reg,"**"));   // ab3f**fa**
var reg = /\d{2}/g;
var str = "ab3f12fa34";
console.log(str.match(reg));   // ["12", "34"]
var reg = /\d{2}/g;
var str = "ab3f12fa34";
console.log(str.split(reg));   // ["ab3f", "fa", ""]
var pattern = /box/i;
var str = 'this is a box,that is a box';
alert(str.match(pattern));          //不是全局匹配,将返回一个box

var pattern = /box/ig;
var str = "this is a box,that is a box";
alert(str.match(pattern));          //开启了全局,这里将返回所有满足条件的字符串,所以是box,box

var pattern = /Box/ig;          //开启全局替换
var str = "this is a box,that is a Box";
alert(str.replace(pattern,"dog"));          //找到字符串中和模式相同的字符串,用新的字符串dog替换

var pattern = /Box/i;
var str = "this is a box ,that is a box";
alert(str.replace(pattern,"dog"));          // 局部匹配,只将第一个字符串匹配成dog(this is a dog,that is a box)

var pattern = /Box/i;
var str = "this is a box ,that is a box";
alert(str.search(pattern));             //返回pattern第一次出现的位置,只要有就返回一个数,没有就返回-1,所以search没有全局与局部之分

var pattern = /hello/i;
var str = "this is a box ,that is a box";
alert(str.search(pattern));                 //str中没有与模式相匹配的字符串,所以这个返回-1

var pattern = / /ig;
var str = "this is a box ,that is a box";
alert(str.split(pattern));              //返回一个数组,包含了按照pattern划分之后的字符串数组
上一篇下一篇

猜你喜欢

热点阅读