js RegEx条件替换为捕获的组 [英] js RegEx conditional replace with captured group
问题描述
我正在尝试使用javascript中的正则表达式来格式化网址...
I am trying to format a url using regex in javascript...
输入: http://www.google.com
或 https://www.yahoo.com
我正在使用此正则表达式捕获/(http \:\/\/| https \:\/\/){0,1}(.*)/
I am using this regex to capture /(http\:\/\/|https\:\/\/){0,1}(.*)/
所以 $ 1
就是说它是 http
还是 https
和 $ 2
其余的URL ...
so $1
is saying is it http
or https
and $2
rest of the url...
现在我想将 http
替换为 1
,将 https
替换为 2
,以便输出如下所示:
Now I want to replace http
with 1
and https
with 2
so that the output should like below:
1www.google.com
和 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"
这篇关于js RegEx条件替换为捕获的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!