admin管理员组文章数量:1278981
How to remove duplicate slashes and trailing slash using regex?
For example:
origin URL:
http://localhost:8080////app//user/login///
to
http://localhost:8080/app/user/login
How to remove duplicate slashes and trailing slash using regex?
For example:
origin URL:
http://localhost:8080////app//user/login///
to
http://localhost:8080/app/user/login
Share
Improve this question
edited Jan 10, 2020 at 8:22
jonrsharpe
122k30 gold badges267 silver badges474 bronze badges
asked Jun 15, 2015 at 12:19
AwakeningAwakening
3,7958 gold badges36 silver badges53 bronze badges
6
-
yourString.split(/\/{1,}/).filter(a=>!a.match(/^\s*$/)).join('/').replace(':/','://');
if ES6 is okay. – Sebastian Simon Commented Jun 15, 2015 at 12:27 - @Xufox I think it is a good question to show powerful regex, I don't understand why people vote against me and close my question. The closer must don't know the best answer!!! – Awakening Commented Jun 15, 2015 at 12:33
- Downvoting on this question is not appropriate. The question is not bad. – cezar Commented Jun 15, 2015 at 12:36
- 1 meta.stackoverflow./questions/285733 Read this. – Sebastian Simon Commented Jun 15, 2015 at 12:40
- 2 @cezar Still doesn’t show enough research effort (what has he/she tried?). – Sebastian Simon Commented Jun 15, 2015 at 12:46
2 Answers
Reset to default 11Here is a simple regex based approach.
var url = 'http://localhost:8080////app//user/login///';
var sanitized = url
.replace(/^http\:\/\//, '') // remove the leading http:// (temporarily)
.replace(/\/+/g, '/') // replace consecutive slashes with a single slash
.replace(/\/+$/, ''); // remove trailing slashes
url = 'http://' + sanitized;
// Now url contains "http://localhost:8080/app/user/login"
Here is an option with using raw strings:
var result = String.raw`http://localhost:8080////app//user/login///`.replace(/\/+/g, "/");
The replace pattern matches every appearance of a slash once or more times and replaces it with a single slash.
本文标签: javascriptRemove duplicate slashes and trailing slashStack Overflow
版权声明:本文标题:javascript - Remove duplicate slashes and trailing slash - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741214540a2359789.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论