作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
var test = https://test.com///?abc=def//&test=1e
console.log(test.replace(/[\/{2,}]+/g,'/'));
我想将所有 //+ 替换为单个 /,但不应更改 https://。
我试过
(!:)[[/{2,}]+
但它不起作用。
如何将除 https://之外的所有//+ 替换为单个/?
最佳答案
我们可以利用replace
replacement callback参数如下:
我们只捕获前面没有 http/s 的连续 /
。由于 https://
与 (?:https?:\/\/)
匹配,但我们使用 ?:
丢弃该捕获组group 不会作为回调函数中的 capture
参数出现。现在 capture
参数仅包含正则表达式的最后一部分:(\/+)
我们现在将其替换为单个 /
let test = 'https://test.com///?abc=def//&test=1e';
const regex = /(?:https?:\/\/)|(\/+)/g;
test = test.replace(regex, (match, capture) => capture ? '/' : match);
console.log(test);
ES2018 答案
RegExp Lookbehind Assertions进入 ES2018,所以下面的正则表达式可以:
const test = 'https://test.com///?abc=def//&test=1e';
test.replace(/(?<!https?:)\/+/g, '/');
关于javascript - 正则表达式,如何在没有 ://的情况下选择//+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49684055/
我是一名优秀的程序员,十分优秀!