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
 |  Show 1 more ment

2 Answers 2

Reset to default 11

Here 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