【问题标题】:js RegEx conditional replace with captured groupjs RegEx 条件替换为捕获的组
【发布时间】:2014-07-03 03:08:44
【问题描述】:

我正在尝试在 javascript 中使用正则表达式格式化 url...

输入:http://www.google.comhttps://www.yahoo.com

我正在使用这个正则表达式来捕获/(http\:\/\/|https\:\/\/){0,1}(.*)/

所以$1 是说是httphttps$2 其余的网址...

现在我想将 http 替换为 1https 替换为 2 以便输出如下所示:

1www.google.com2www.yahoo.com

我使用了下面的代码,但它不起作用...

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

任何人都知道如何做到这一点...??谢谢...

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    使用正则表达式的解决方案

    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"
    

    【讨论】:

      【解决方案2】:

      您使用的正则表达式不好:它可以匹配字符串中间的http,并且即使不需要它也会尝试匹配整个字符串

      改用这个

      url.replace(/^http(s)?:\/\//, function(match, secure) {
          return secure ? "2" : "1"
      })
      

      【讨论】:

        【解决方案3】:

        url.replace('https','2').replace('http','1')

        不知道为什么要这样做

        【讨论】:

        • 我想要使用正则表达式的解决方案......所以当然应该有一个原因......我真正的问题更复杂,我想使用单个正则表达式替换而不是 15 个替换你的……
        【解决方案4】:
        url.replace(/(http\:\/\/|https\:\/\/){0,1}(.*)/,function($1, $2, $3) {
            if($2 == 'https://') {
                return "2" + $3
            } else {
                return "1" + $3
            }
        });
        

        说明 - 替换函数如何与 RegEx 配合使用

        replace(<RegEx>, handler)
        

        参数 - $1, $2, $3 ... 是 RegEx 的结果。正则表达式模式中的每个捕获组都可以使用 $N 表示法在替换字符串中使用,其中“N”是捕获组的索引:

        【讨论】:

        • 您回答的问题与 xecgr 的回答相同...您应该投赞成票...
        【解决方案5】:
        url.replace(/(http\:\/\/|https\:\/\/){0,1}(.*)/, ("$1"=="http://"?"1":"2")+"$2");
        

        应该做到这一点,而不必引入 lambda 函数并且对现有代码进行最少的修改。您的正则表达式的问题在于您正在捕获 :// 并且没有与之进行比较,并且 "http://" == "http" 将始终评估为 false。

        【讨论】:

        • 感谢您的回答...我在我的问题中写错了...即使您与 http:// 比较它说 false...
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-04
        • 2011-02-24
        • 1970-01-01
        • 1970-01-01
        • 2019-03-08
        相关资源
        最近更新 更多