前端之家收集整理的这篇文章主要介绍了
每天一点,学JavaScript【正则】,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
var pattern = new RegExp
(pattern,attributes)
or simply
var pattern = /
pattern/
attributes
[ ]
-
[abc]
括号内任何一个字符
-
[\^abc]
任何一个不在括号之间的字符
-
[0-9]
0到9之间的任何一个十进制数字
-
[a-z]
从小写a到小写z
-
[A-Z]
从大写A到大写Z
-
[a-Z]
从小写a到大写Z
-
[x|y]
x或者y
量词
-
p+
包含p的任何字符串
-
p{2,3}
包含2个或3个p的字符串
-
p{2,}
包含2个及2个以上的字符串
-
p$
末尾是p的字符串
-
^p
以p开头的字符串
\
-
.
单个字符
-
\s
空白字符(换行,空格,制表符)
-
\S
非空白字符
-
\d
数字字符(0-9)
-
\D
非数字字符
-
\w
单词字符(包括AZ,按照,0-9)
-
\W
非单词字符(特殊符号)
-
[\b]
文字退格(特例)
i
一次
g
全局
y
指定lastIndex
let reg = /
javascript/
iy
reg.lastIndex
= 7 //从index=7开始
.*
贪婪模式 一直匹配到最后一个
RegExp Methods
-
exec()
在字符串参数中执行匹配搜索
-
test()
在字符串参数中测试匹配,返回boolean
Sring Methods
str.search(reg)
str.search(/a/i) // 0 (the first position)
str.search('str')
str.match(reg)
let result = str.match(/fame/i)
console.log( result[0] ) // Fame (the match)
console.log( result.index ) // 0 (at the zero postion)
console.log( result.input ) // "Fame is the thirst of youth" (the string)</code></pre>
str.match( /reg(exp)/i )
str.match( /JAVA(SCRIPT)/i )
括号代表多条件‘or’
result[0] javascript
result[1] script
str.match( /reg/g )
"HO-Ho-ho".match( /ho/ig ) // return HO,Ho,ho
"HO-Ho-ho".match( /h(o)/ig ) // return HO,ho
str.split(regexp | substr,limit)
alert('12-34-56'.split('-')) // [12,34,56]
alert('12-34-56'.split(/-/)) // [12,56]
str.replace(str|reg,str|func)
alert('12-34-56'.replace("-",":")) // 12:34-56
alert( '12-34-56'.replace( /-/g,":" ) ) // 12:34:56
参考