url正则表达式不适用于javascript中的localhost

时间:2015-03-24 11:42:53

标签: javascript html ajax regex

我的代码是:

 <script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
    //bit_url function
    function bit_url(url)
    {
        var url=url;
        var username="username"; // bit.ly username
        var key="bit.ly API key";
        $.ajax({
            url:"http://api.bit.ly/v3/shorten",
            data:{longUrl:url,apiKey:key,login:username},
            dataType:"jsonp",
            success:function(v)
            {
                var bit_url=v.data.url;
                $("#result").html('<a href="'+bit_url+'" target="_blank">'+bit_url+'</a>');
            }
        });
    }

    $("#short").click(function()
    {
        var url=$("#url").val();
        var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
        var urltest=urlRegex.test(url);
        if(urltest)
        {
            bit_url(url);
        }
        else
        {
            alert("Bad URL");
        }
    });
});
</script>

//HTML Code
<input type="text" name="url" id="url"/>
<input type="submit" id="short" value="Submit"/>
<div id="result"></div>`enter code here`

当我给this url时,它既没有给出错误也没有给出短网址。请帮我找出解决此错误的方法。

提前谢谢!

1 个答案:

答案 0 :(得分:2)

bit.ly不再对localhost个网址进行编码 - see this