Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

js RegEx conditional replace with captured group

I am trying to format a url using regex in javascript...

Input: http://www.google.com or https://www.yahoo.com

I am using this regex to capture /(http\:\/\/|https\:\/\/){0,1}(.*)/

so $1 is saying is it http or https and $2 rest of the url...

Now I want to replace http with 1 and https with 2 so that the output should like below:

1www.google.com and 2www.yahoo.com

I used the below code but it's not working...

var url = "http://www.microsoft.com";
url.replace(/(http\:\/\/|https\:\/\/){0,1}(.*)/, ("$1"=="http://"?"1":"2")+"$2");
// output: 2www.microsoft.com

url.replace(/(http\:\/\/|https\:\/\/){0,1}(.*)/, ("$1"=="http://")+"$2");
// output: falsewww.microsoft.com

Anybody know how to do that...?? thanks...

like image 282
NazKazi Avatar asked Dec 07 '22 01:12

NazKazi


1 Answers

A solution using your regex

var url1= 'http://www.google.com';
var url2= 'https://www.yahoo.com';
url1.replace(/(http\:\/\/|https\:\/\/){0,1}(.*)/, function (g1,g2,g3) { 
    var prefix =''; 
    if(g2 == 'https://') {
        prefix = '2'
    } else{ 
        prefix='1'
    } 
    return prefix + g3
})
//url1.replace(...) //"1www.google.com"
//url2.replace(...) //"2www.yahoo.com"
like image 176
xecgr Avatar answered Dec 18 '22 08:12

xecgr