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...
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"
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With