js 正则表达式,分组,非捕获或 环视的使用

时间:2021-01-14 01:55:18

定位一个字符串中,匹配与定位重复字符中的最后一个字符:

例子:

<script type="text/javascript">
var str="http://www.cnblogs.com/cn-coder//img.ipg";
var patt1 = /\/\/(?!.*\/\/)/ig;
document.write(str.replace(patt1,"/"));//http://www.cnblogs.com/cn-coder/img.ipg
</script>
var str="http://www.baidu.com/xxxx//aaa/bbb/img.ipg";
var patt1 = /\/\/(?!.*\/)/ig;
document.write(str.replace(patt1,"/"));

另一种方式:

document.write("<BR>");
var str2="http://www.baidu.com//xxxx//img.ipg";
var patt2 =new RegExp('/(?!.*\/\/)/','ig');
document.write(str2.replace(patt2,"/"));