我有一组网址,需要获取的特定部分。网址格式为:

http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg


我需要获取1234567位并将其存储在var中。

最佳答案

通过使用函数检查URL,您应该能够使其与JSON字符串一起使用。这样的事情应该起作用:

function checkForMatches(str) {
    var res = str.match(/.*\/(.*)_1.jpg/);
    if(res) {
        output = res[res.length-1];
    } else {
        output = false;
    }
    return output;
}


$.get("test.php", function (data) {
    // now you can work with `data`
    var JSON = jQuery.parseJSON(data); // it will be an object
    $.each(JSON.deals.items, function (index, value) {
        //console.log( value.title + ' ' + value.description );
        tr = $('<tr/>');
        tr.append("<td>" + "<img class='dealimg' src='" + value.deal_image + "' >" + "</td>");
        tr.append("<td>" + "<h3>" + value.title + "</h3>" + "<p>" + value.description + "</p>" + "</td>");
        //tr.append("<td>" + value.description + "</td>");
        tr.append("<td> £" + value.price + "</td>");
        tr.append("<td class='temperature'>" + value.temperature + "</td>");
        tr.append("<td>" + "<a href='" + value.deal_link + "' target='_blank'>" + "View Deal</a>" + "</td>");

        myvar = checkForMatches(value.deal_link);
        if(myvar == false) {
            myvar = value.deal_link; //if no matches, use the full link
        }


        tr.append("<td>" + "<a href='" + myvar + "' target='_blank'>" + "Go To Argos</a>" + "</td>");
        $('table').append(tr);
    });
});





前面有更多基本示例。

您可以使用正则表达式查找匹配项。

这样的事情会起作用:

var str = "http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg";
var res = str.match(/.*\/(.*)_1.jpg/);
alert(res[1])


如果想进一步使用它,可以创建一个函数并传递要测试的字符串,如果找到则返回匹配的值,如果不存在匹配则返回boolean false。

这样的事情会起作用:

function checkForMatches(str) {
    var res = str.match(/.*\/(.*)_1.jpg/);

    if(res) {
        output = res[res.length-1];
    } else {
        output = false;
    }

    return output;

}


alert(checkForMatches("http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg"))
alert(checkForMatches("this is an invalid string"))


您可以在这里看到它的工作:https://jsfiddle.net/9k5m7cg0/2/

希望有帮助!

关于javascript - 获取URL的特定部分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35158448/

10-16 20:12