replace配合正则表达式的使用技巧,惊爆你的大脑
2017-03-31 00:11
274 查看
正则 replace 第二个参数
基本语法:
.replace( regex, string|function ) -> string
第二个参数如果是函数, 表示, 前面字符串被匹配的结果由函数的返回值所替换.
也就是说, 匹配到一次函数就会调用一次, 有匹配结果函数就会调用多少次.
案例:
‘今天123很好456你呢?’ => ‘今天一二三很好四五六你呢?’
str.replace( /\d/g, function ( res ) {
return ‘零一二三四五六七八九’.charAt( res - 0 );
});
基本语法:
.replace( regex, string|function ) -> string
第二个参数如果是函数, 表示, 前面字符串被匹配的结果由函数的返回值所替换.
也就是说, 匹配到一次函数就会调用一次, 有匹配结果函数就会调用多少次.
在函数中有参数, 表示的是匹配的结果与组
案例:
‘今天123很好456你呢?’ => ‘今天一二三很好四五六你呢?’
str.replace( /\d/g, function ( res ) {
return ‘零一二三四五六七八九’.charAt( res - 0 );
});
将驼峰命名法转换成连字符的命名 getElementsByTagName -> get-elements-by-tag-name // /(.)([A-Z])/ str.replace( /(.)([A-Z])/g, function ( _, a, b ) { return a + '-' + b.toLowerCase(); }); 'get-element-by-id' => 'getElementById' 'get-element-by-id'.replace( /-(.)/g, function ( _, first ) { return first.toUpperCase(); }); 'getElementById' => 'get-element-by-id' 'AAA' => 'a-a-a' 'getElementById'.replace( /(.)([A-Z])/g, function( _, prev, next ) { return prev + '-' + next.toLowerCase(); }).replace( /(.)([A-Z])/g, function( _, prev, next ) { return prev + '-' + next.toLowerCase(); }) // 案例 'hello, world' 正则中 \s表示匹配非空字符串 console.log('hello, world'.replace( /,|\s/g, '' ).split( '' ).join( ',' )) // var str = 'hello, world'.replace( /,|\s/g, '' ); // var arr = str.split( '' ); // var res = arr.join( ',' );
相关文章推荐
- JavaScript中String对象的match()、replace() 配合正则表达式使用
- .net中的正则表达式使用高级技巧 (二)(from internet)
- .net中的正则表达式使用高级技巧 (四)
- .net中的正则表达式使用高级技巧 (二)
- .NET正则表达式使用高级技巧之反向引用
- .net中的正则表达式使用高级技巧 (二)
- .net中的正则表达式使用高级技巧 (三)
- .net中的正则表达式使用高级技巧 (一)
- .net中的正则表达式使用高级技巧 (三)
- .net中的正则表达式使用高级技巧 (二)
- .net中的正则表达式使用高级技巧
- .net中的正则表达式使用高级技巧 (一)
- .net中的正则表达式使用高级技巧 (四)(from internet)
- .net中的正则表达式使用高级技巧 (四)
- .net中的正则表达式使用高级技巧
- net中的正则表达式使用高级技巧 (二)
- JS中的正则表达式小小的技巧---Test方法的使用
- 正则表达式在线手册及使用指南技巧
- .net中的正则表达式使用高级技巧 (三)
- .net中的正则表达式使用高级技巧 (一)