正则表达式的使用

RegExp是正则表达式的缩写。

当检索某个文本时,可以使用一种模式来描述要检索的内容。RegExp就是这种模式。

test方法

test()方法检索字符串中的指定值。返回值是true或false。

var pat = /m/;

var str = “this m id code”;

console.log(pat.test(str));//true

exec方法

exec()方法检索字符串中的指定值。返回值是被找到的值。如果没有发现匹配,则返回null。

var pat = /hello/;

console.log(pat.exec(“oh hello world”));//返回hello

正则表达式类型

/pattern/attributes

参数attributes 是一个可选的字符串,常用属性“g”,”i”,分别用于指定全局匹配、区分大小写的匹配。

字符串正则

1.search  字符串查找

var  str = “hello world!”;

console.log(str.search(/World/));//-1

console.log(str.search(/World/i));//6

2.match  字符串匹配

var str = “1 str 333 eqeef 33”;

console.log(str.match(/\d+/));//[1]

console.log(str.match(/\d+/g));//[1,333,33]

3.replace 字符串替换

var str = “hello world,world is nice!”;

console.log(str.replace(/world/,”xu”));//hello xu,world is nice!

console.log(str.replace(/world/ig,”xu”));//hello xu,xu is nice!

4.split  字符串分割

var str = “hello xu,oh i am qian”;
console.log(str.split(“”));//[“h”, “e”, “l”, “l”, “o”, ” “, “x”, “u”, “,”, “o”, “h”, ” “, “i”, ” “, “a”, “m”, ” “, “q”, “i”, “a”, “n”]
console.log(str.split(/\s+/));//[“hello”, “xu,oh”, “i”, “am”, “qian”]

posted @ 2018-03-09 09:46  xqr_scl  阅读(137)  评论(0编辑  收藏  举报