删除字符串的前半部分,但在javascript或jquery中保留后半部分

时间:2013-06-06 19:04:30

标签: javascript jquery

我最近created my own personal portal page取代iGoogle,因为它将在今年晚些时候关闭。一切正常,除了我输入的RSS源之一输出的网址如下:http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNFEguC5pqagsWkkW_y_EjYj9n1bMg&url=http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305

单击时会转到错误的网址页面。如何删除该网址的前半部分,使其仅包含从第二个http://

开始的部分

奇怪,但这里链接工作正常......

刚刚意识到问题在于,&符号正在转变成打破链接的实体......

3 个答案:

答案 0 :(得分:0)


编辑:代码已更新,jsFiddle已添加


<强> HTML:

<input id="schnitzel" type="text" value="http://www.google.com/http://www.real-foo.bar/" />
<input type="button" onclick="$('#schnitzel').val(window.firstHTTP($('#schnitzel').val()));" value="&raquo;" />

<强> JavaScript的:

window.firstHTTP = function (furl = "") {
    var chunked = furl.split("http://");
    return (chunked && chunked[2]) ? ("http://" + chunked[2]) : furl;
};

<强> JS-小提琴:

http://jsfiddle.net/Rm5bU/

答案 1 :(得分:0)

试试这个。通用方法。

function queryString(parameter, url) {
    var a = document.createElement("a");
    a.href = url;        
    var loc = decodeURIComponent(a.search.substring(1, a.search.length));
    var param_value = false;
    var params = loc.split("&");

    for (var i = 0; i < params.length; i++) {
        param_name = params[i].substring(0, params[i].indexOf('='));
        if (param_name == parameter) {
            param_value = params[i].substring(params[i].indexOf('=') + 1)
        }
    }

    if (param_value) {
        return encodeURIComponent(param_value);
    }
    else {
        return "";
        //param not found
    }
}

var secondHTTP = queryString("url", 'http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNFEguC5pqagsWkkW_y_EjYj9n1bMg&url=http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305');

答案 2 :(得分:0)

var str = "http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNFEguC5pqagsWkkW_y_EjYj9n1bMg&url=http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305";

var url = decodeURIComponent(str.split(/https?:/ig).pop());

将导致

"//www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305"

var url = decodeURIComponent(str.match(/^http.+(http.+)/i)[1]);

将导致

"http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305"