通过一些例子来学习正则表达式摘录,js正则函数match、exec、test、search、replace、split

⚠️ 创建了一个新仓库,方便专门搜集讨论正则相关内容。顺便将下面内容整理到了新仓库。=> @jaywcjlove/regexp-example

一些匹配方法

去除首尾的

//去除首尾的‘/’
input = input.replace(/^\/*|\/*$/g,'');

javascript:; 、javascript:void(0)

'javascript:;'.match(/^(javascript\s*\:|#)/);
//["javascript:", "javascript:", index: 0, input: "javascript:;"]

匹配

var str = "access_token=dcb90862-29fb-4b03-93ff-5f0a8f546250; refresh_token=702f4815-a0ff-456c-82ce-24e4d7d619e6; account_uid=1361177947320160506170322436";
str.match(/account_uid=([^\=]+(\;)|(.*))/ig);
//=> ["account_uid=1361177947320160506170322436"]

匹配一些字符

var str = 'asdf html-webpack-plugin for "index/index.html" asdfasdf';
str.match(/html-webpack-plugin for \"(.*)\"/ig);
console.log(RegExp.$1) //=>index/index.html

关键字符替换

'css/[hash:8].index-index.css'.replace(/\[(?:(\w+):)?(contenthash|hash)(?::([a-z]+\d*))?(?::(\d+))?\]/ig,'(.*)');
//=> css/(.*).index-index.css

替换参数中的值

```js
var str = '';
str.replace(/]manifest="([^"])"[^>]*>/,function(word){
return word.replace(/manifest="([^"]*)"/,'manifest="'+url+'"');
}).replace(/]*\>)/,function(word){
if(word.indexOf('manifest')) return word;
return word.replace('