js RegEx条件替换为捕获的组 [英] js RegEx conditional replace with captured group

查看:51
本文介绍了js RegEx条件替换为捕获的组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆