简体   繁体   中英

Regular Expression To Replace Double Slashes with Javascript

I would like to remove any forward slashes in URL that are more than once in the sequence. So far:

var temp = "/path//to/middle//nowhre/avator2.jpg";
temp.replace(/\/\//,'/');

This works only for double slashes and only once but i would like it removes any number slashes that are more than once and do it for any occurance in the URL. I also tried

temp.replace(/*[/+]*/,'/');

but this doesn't work. Any help much appreciated. Thank You

用单个/替换两个或多个/所有序列: temp.replace(/\\/{2,}/g,'/');

你应该有全球

temp.replace(/[\/]+/g, '/')

You need to use the g (global modifier) to replace all occurrences. Use the following for two or more slashes.

var r = "/path//to/middle//nowhre/avator2.jpg".replace(/\/{2,}/g, '/');
console.log(r); //=> "/path/to/middle/nowhre/avator2.jpg"

For URL's, I suggest the following:

var s = "http://www.some-url.com//path//to";
var res = s.replace(/(https?:\/\/)|(\/)+/g, "$1$2");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM