您的位置:首页 > 其它

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 );

});

将驼峰命名法转换成连字符的命名
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( ',' );
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息