codecamp

正则表达式(Regular expressions)

JavaScript内建支持正则表达式。他们被双斜线分隔:

/^abc$/
/[A-Za-z0-9]+/

方法 test():测试是否匹配(Method test(): is there a match?)

> /^a+b+$/.test('aaab')
true
> /^a+b+$/.test('aaa')
false

方法 exec():匹配和捕获组(Method exec(): match and capture groups)

> /a(b+)a/.exec('_abbba_aba_')
[ 'abbba', 'bbb' ]

返回的数组第一项(索引为0)是完整匹配,捕获的第一个分组在第二项(索引为1),等。有一种方法可以反复调用获取所有匹配。

方法 replace():搜索并替换(Method replace(): search and replace)

> '<a> <bbb>'.replace(/<(.*?)>/g, '[$1]')
'[a] [bbb]'

replace的第一个参数必须是正则表达式,并且开启全局搜索(/g 标记),否则仅第一个匹配项会被替换。有一种方法使用一个函数来计算替换项。

深入阅读

数组(Arrays)
数学(Math)
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }