正则表达式在每个编程语言中都是不可缺少的,分享一下 javascript 正则表达式的常用方法
exec
功能:在字符串中执行匹配检索,返回结果数组
const reg = /^a/
const str = 'abc123'
console.log(reg.exec(str))
// [ 'a', index: 0, input: 'abc123' ]
test
功能:在字符串测试模式匹配,返回 true 或 false
const str = 'cat and dog';
const patt = /cat/g;
console.log(patt.test(str));
// true
match
功能:找到一个或多个正则表达式的匹配
const str = 'Is this all there is?'
console.log(str.match(/is/gi));
// [ 'Is', 'is', 'is' ]
replace
功能:替换与正则表达式匹配的子串
const str = '我是 replace';
console.log(str.replace(/replace/i, '替换'));
// 我是替换
search
功能:检索与正则表达式相匹配的值
const str = '我是 search';
console.log(str.search(/search/i));
// 2
split
功能:把字符串分割为字符串数组
const str = 'How are';
console.log(str.split(''));
// [ 'H', 'o', 'w', ' ', 'a', 'r', 'e' ]
console.log(str.split('',3));
// [ 'How', 'are' ]
console.log(str.split('o'));
// [ 'H', 'w are' ]
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
展开阅读更多