JavaScript regex - how to select all double slashes except followed by colon

I need some help with RegEx, it may be a basic stuff but I cannot find a correct way how to do it. Please help!

So, here's my question:

I have a list of URLs, that are invalid because of double slash, like this: http://website.com//wp-content/folder/file.jpg, to fix it I need to remove all double slashes except the first one followed by colon (http://), so fixed URL is this: http://website.com/wp-content/folder/file.jpg.

I need to do it with RegExp.

Variant 1

url.replace(/\/\//g,'/'); // => http:/website.com/wp-content/folder/file.jpg

will replace all double slashed (//), including the first one, which is not correct.


example here: https://regex101.com/r/NhCVMz/2

Answer:1

You may use

url = url.replace(/(https?:\/\/)|(\/){2,}/g, "$1$2")

See the regex demo

Note: a ^ anchor at the beginning of the pattern might be used if the strings are entire URLs.

This pattern will match and capture http:// or https:// and will restore it in the resulting string with the $1 backreference and all other cases of 2 or more / will be matched by (\/){2,} and only 1 occurrence will be put back into the resulting string since the capturing group does not include the quantifier.

Answer:2

When I try to create a token for a user like in this code : const jwt = require('jsonwebtoken'); const passport = require('passport'); const Patient = require('../models').Patient; module.exports = {...

When I try to create a token for a user like in this code : const jwt = require('jsonwebtoken'); const passport = require('passport'); const Patient = require('../models').Patient; module.exports = {...

Currently in React, I am using array.map(function(text,index){}) to iterate through an array. But, how am I going to iterate through two arrays simultaneously using map? EDIT var sentenceList = ...

Currently in React, I am using array.map(function(text,index){}) to iterate through an array. But, how am I going to iterate through two arrays simultaneously using map? EDIT var sentenceList = ...

I want to add dynamic directive inside another directive tempalte. As you see I want to add another directive inside a directive template How do add those dynamic directive there Please help return {...

I want to add dynamic directive inside another directive tempalte. As you see I want to add another directive inside a directive template How do add those dynamic directive there Please help return {...

I have read several tutorials about closures. Some tutorials have some information about execution context. I am confused that execution context and closure seem to the same thing.Does anyone can ...

I have read several tutorials about closures. Some tutorials have some information about execution context. I am confused that execution context and closure seem to the same thing.Does anyone can ...

  1. closure execution context