首页 > 如何用js正则拆分斜杠/之间的字符?

如何用js正则拆分斜杠/之间的字符?

如:route=module/pavcarousel&module_id=31&token=ee73833ad763eeecbed4b46289df5d64/test

需要拆分成:
route=module
pavcarousel&module_id=31&token=ee73833ad763eeecbed4b46289df5d64
test

三段,如果后面有更多段的就继续拆分

不使用split(),用正则如何写


由于js不支持断言,所以你可以匹配含有/号的然后替换一下,使用 \/.+?(?=\/)出带有前缀/然后替换/或substring。对于你这个特殊的首先要求尾部添加/号,然后通过\w.+?(?=\/)匹配,之后每个去掉前缀/


  var str = 'route=module/pavcarousel&module_id=31&token=ee73833ad763eeecbed4b46289df5d64/test';
var arr = str.match(/([^\/]+)/g);
console.log(arr);

用split就挺好啊,干嘛要这么折腾呢

如果非要匹配子串的模式,当然可以这样 url.match(/.*?\//g)
只要手动在url结尾补上"/" 就能把所有字串过滤出来

当然对于这种url来说 要分割"/",当然是split最方便了,要知道split也是正则表达式,只不过匹配的是分隔符而已


如果用exec分组怎么实现呢

【热门文章】
【热门文章】