通过JS regex从字符串中检索数字

时间:2014-12-10 07:57:15

标签: javascript regex

我试图从字符串中检索某个数字。但我无法弄清楚如何隔离我需要的部分。

字符串:

https://intra.site.com/departments/travel/Lists/Booking/fd_Item_Display.aspx?List=8af14ed7-3bde-4ec0-b62a-9516324c967e&ID=15&Source=https%3A%2F%2Fintra%2Emonjasa%2Ecom%2Fdepartments%2Ftravel%2FPages%2Fdefault%2Easpx&ContentTypeId=0x0100B7DC1AFF519B6343BC8014EB1910DFAB

我需要ID=之后的数字。

我没有运气就尝试使用string.replace()

我怎么能用正则表达式做到这一点?

3 个答案:

答案 0 :(得分:3)

检查出来:

function getParameterByName(url, parameter) {
   var regex = new RegExp("[\\?&]" + parameter + "=([^&#]*)"),
   results = regex.exec(url);
   return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var url = 'https://intra.site.com/departments/travel/Lists/Booking/fd_Item_Display.aspx?List=8af14ed7-3bde-4ec0-b62a-9516324c967e&ID=15&Source=https%3A%2F%2Fintra%2Emonjasa%2Ecom%2Fdepartments%2Ftravel%2FPages%2Fdefault%2Easpx&ContentTypeId=0x0100B7DC1AFF519B6343BC8014EB1910DFAB';
var parameter = 'ID';

console.log( getParameterByName(url, parameter) );
// Log => 15

答案 1 :(得分:1)

您可以使用:

var str = 'https://intra.site.com/departments/travel/Lists/Booking/fd_Item_Display.aspx?List=8af14ed7-3bde-4ec0-b62a-9516324c967e&ID=15&Source=https%3A%2F%2Fintra%2Emonjasa%2Ecom%2Fdepartments%2Ftravel%2FPages%2Fdefault%2Easpx&ContentTypeId=0x0100B7DC1AFF519B6343BC8014EB1910DFAB';
var id = (str.match(/&ID=([^&]*)/i) || ['', ''])[1];
//=> 15

答案 2 :(得分:1)

试试这个。更容易理解。

    

    function getID()
    {
      
    var str = "https://intra.site.com/departments/travel/Lists/Booking/fd_Item_Display.aspx?List=8af14ed7-3bde-4ec0-b62a-9516324c967e&ID=15&Source=https%3A%2F%2Fintra%2Emonjasa%2Ecom%2Fdepartments%2Ftravel%2FPages%2Fdefault%2Easpx&ContentTypeId=0x0100B7DC1AFF519B6343BC8014EB1910DFAB";

    var id = str.match(/ID=(\d*)/)[1];        
     
    alert(id);
      
    }
<input type="button" onclick="getID()" value="Click me">