首页 新闻 赞助 找找看

js正则匹配字符串中的url地址

0
悬赏园豆:10 [待解决问题]
有字符串如下:
手机的饭卡手机的疯狂拉升金光华附近撒旦回复
http://www.xxx.com/骄傲深刻理解的疯狂升级啊对抗疗法。

其中url地址可能是如下三种情况:
http://www.xxx.com/

http://www.xxx.com/mall/default.aspx
http://www.xxx.com/mall/default.aspx?id=2

现在想用js配合正则,将已有参数加入到字符串中,参数是re=100,
所以匹配之后的字符串中url地址部分可能是如下三种情况:
http://www.xxx.com/?re=100
http://www.xxx.com/mall/default.aspx?re=100
http://www.xxx.com/mall/default.aspx?id=2&re=100

求大侠给解
Lison Liou的主页 Lison Liou | 初学一级 | 园豆:194
提问于:2013-03-07 18:54
< >
分享
所有回答(6)
0

我感觉这个主要是判断有无传参的问题,重点就是判断问号

1)有问号(一般就表示有参数了),那么就加上&name=value

2)没有问号,那么就加上?name=value

yevon | 园豆:306 (菜鸟二级) | 2013-03-07 19:43
0

if(url.indexOf("?")==-1){url=url+"?re=100";}

else{url=url+"&re=100";}

马小白 | 园豆:188 (初学一级) | 2013-03-08 10:39

嗯就是这么写的,但是这么写有个前提是字符串中的url必须在最后的位置

支持(0) 反对(0) Lison Liou | 园豆:194 (初学一级) | 2013-03-08 10:55

@Lison Liou: 上面这么写有什么问题?没看明白

支持(0) 反对(0) 程序猿小卡 | 园豆:386 (菜鸟二级) | 2013-03-10 15:44
0

小白马

Angkor--:-- | 园豆:1086 (小虾三级) | 2013-03-08 11:56
0

我懂你意思了。有两个问题:

1.http://www.xxx.com/mall/default.aspx 最后是不是 一定是mall/default.aspx ,还是说你只是举了个例子?

2.“前提是字符串中的url必须在最后的位置”, 你怎么界定url结束了,比如

http://www.xxx.com/mall/default.aspx?id=32其他内容

这一行中没法确定id的值到底是多少

acjialiren | 园豆:191 (初学一级) | 2013-03-14 14:37
0

先匹配url 然后在url加上参数,最后替换掉url

LineZero | 园豆:242 (菜鸟二级) | 2013-03-27 09:31
0
实例
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Template</title>
    </head>
    <body>
        <div id="wrapper">
            其中url地址可能是如下三种情况:
http://www.xxx.com/打算<a>dsd</a>的撒http://www.xxx.com/mall/default.aspx打算
http://www.xxx.com/mall/default.aspx?id=2打算的

现在想用js配合正则,将已有参数加入到字符串中,参数是re=100,
所以匹配之后的字符串中url地址部分可能是如下三种情况:
        </div>
    </body>
    <script type="text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript">
        //http://q.cnblogs.com/q/47279/

        var cl = console.log;
        var content = $('#wrapper').html();
        //cl(content);
        //http://www.xxx.com/mall/default.aspx?id=2
        var reg = /http:\/\/www.xxx.com\/[\w\/\.?=]*/gi;
        //var match = content.match(reg);
        //cl(match);
        var newC = content.replace(reg,function(){
            //console.log(arguments[0])
            var matchedStr = arguments[0];
            if(matchedStr.indexOf("?") == -1){
                return matchedStr + "?re=100";
            }else{
                return matchedStr + "&re=100";
            }
        });
        cl(newC);

        //http://www.cnblogs.com/mxw09/archive/2010/08/12/1797905.html 供参考
        //http://www.aslibra.com/blog/post/js_replaceAll.php
    </script>
</html>

应该能解决了。

积跬步 | 园豆:214 (菜鸟二级) | 2013-05-02 23:37
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册