Reputation: 2775
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...
Upvotes: 9
Views: 9788
Reputation: 24104
regexp you are using isn't good: it can match http in the middle of the string and it tries to match whole string even though it is not needed
use this instead
url.replace(/^http(s)?:\/\//, function(match, secure) {
return secure ? "2" : "1"
})
Upvotes: 2
Reputation: 1326
url.replace(/(http\:\/\/|https\:\/\/){0,1}(.*)/, ("$1"=="http://"?"1":"2")+"$2");
should do the trick without having to introduce lambda functions and with minimal modification to your existing code. The problem with your regex is that you were capturing the ://
and not comparing with that, and "http://" == "http"
will always evaluate to false.
Upvotes: -1
Reputation: 2671
url.replace(/(http\:\/\/|https\:\/\/){0,1}(.*)/,function($1, $2, $3) {
if($2 == 'https://') {
return "2" + $3
} else {
return "1" + $3
}
});
Explanation - How replace function works with RegEx
replace(<RegEx>, handler)
Parameters - $1, $2, $3 ... are result of the RegEx. Each captured group in the regular expression pattern can be used within the replacement string using the $N notation, where "N" is the index of the captured group:
Upvotes: 0
Reputation: 5193
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"
Upvotes: 21
Reputation: 4052
url.replace('https','2').replace('http','1')
Not sure why you would want to do this though
Upvotes: 1