var regex = /\w+/;
// 或者
var regex = new RegExp('\\w+');
RegExp.prototype.test(str); RegExp.prototype.exec(str);
// RegExp#test()
var regex = /hello/;
var result = regex.test('hello world'); // true
// RegExp#exec()
var regex = /hello/;
var result = regex.exec('hello world'); // ['hello']
// (llo)是一个捕获组
var regex = /he(llo)/;
var result = regex.exec('hello world'); // ['hello', 'llo']
String.prototype.search(regexp); String.prototype.match(regexp); String.prototype.split([separator[, limit]]); String.prototype.replace(regexp|substr, newSubStr|function);
// String#search() 'hello world'.search(/hello/); // 0 'hello world'.search(/hi/); // -1
// String#match()
'hello hello'.match(/he(llo)/); // ['hello', 'llo']
// String#match()遇到全局g修饰符时会舍弃捕获组
'hello hello'.match(/he(llo)/g); // ['hello', 'hello']
// RegExp#exec()仍旧包含捕获组
/he(llo)/g.exec('hello hello'); // ['hello', 'llo']
// String#split()
'hello'.split(); // ["hello"]
'hello'.split(''); // ["h", "e", "l", "l", "o"]
'hello'.split('', 3); // ["h", "e", "l"]
// 指定一个非空字符串
var source = 'hello world';
var result = source.split(' '); // ["hello", "world"]
// 或者使用正则表达式
var result = source.split(/\s/); // ["hello", "world"]
如果separtor是一个正则表达式,并且正则中包含捕获组,则捕获组也会出现在结果数组中:
// String#split() 正则捕获组
var source = 'matchandsplit';
var result = source.split('and'); // ["match", "split"]
var result = source.split(/and/); // ["match", "split"]
// 正则中含捕获组
var result = source.split(/(and)/); // ["match", "and", "split"]
// String#replace()
var source = 'matchandsplitandreplace';
var result = source.replace('and', '-'); // "match-splitandreplace"
// 或者
var result = source.replace(/and/, function() {
return '-';
}); // "match-splitandreplace"
// String#replace() 全局替换
var source = 'matchandsplitandreplace';
var result = source.replace(/and/g, '-'); // "match-split-replace"
var result = source.replace(/and/g, function() {
return '-';
}); // "match-split-replace"
// String#replace() 替换函数的参数列表
var source = 'matchandsplitandreplace';
var result = source.replace(/(a(nd))/g, function(match, p1, p2, offset, string) {
console.group('match:');
console.log(match, p1, p2, offset, string);
console.groupEnd();
return '-';
}); // "match-split-replace"
// -> String#search(new RegExp(val.toString()))
'123 123'.search(1); // 0
'true false'.search(true); // 0
'123 123'.search('\\s'); // 3
var o = {
toString: function() {
return '\\s';
}
};
'123 123'.search(o); // 3
// -> String#match(new RegExp(val.toString()))
'123 123'.match(1); // ["1"]
'true false'.match(true); // ["true"]
'123 123'.match('\\s'); // [" "]
var o = {
toString: function() {
return '1(23)';
}
};
'123 123'.match(o); // "123", "23"]
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有