2015-06-10 27 views
4

有URL的数字值在其中。需要提取该数值。但是,URL中的数值位置不是固定的。需要一个通用的方式如何提取。由于值的位置不固定,因此无法使用拆分方法。如何仅从URL中提取数字值javascript或jquery

例如:

1. https:// www.example.com/A/1234567/B/D?index.html 
2. http://www.example.com/A?index.html/pd=1234567 
3. http://www.example.com/A/B/C/1234567?index.html 

所以上述三个URL'S具有一个数字值,其位置不是恒定的。 你能否提供一个通用的方法,我可以得到像“1234567”这样的预期输出。

回答

6

使用基本正则表达式:

"http://www.example.com/A?index.html/pd=1234567".match(/\d+/); 

这返回的第一个系列在字符串中的数字。在上述情况下,我们得到以下内容:

[ "1234567" ] 
+1

给予好评的FGITW :) – Ted

1

这是fiddle

$(this).text().match(/\d+/)[0] 

请注意,这意味着URL中没有其他数字序列! 哪里有!

1

另一个工作的:)

var str ="https:// www.example.com/A/1234567/B/D?index.html"; 
var numArray = []; 
for (var i = 0, len = str.length; i < len; i++) { 
    var character = str[i]; 
    if(isNumeric(character)){ 
     numArray.push(character); 
    } 
} 
console.log(numArray); 
function isNumeric(n) { 
    return !isNaN(parseFloat(n)) && isFinite(n) 
} 

退房的FIDDLE LINK

1

添加到@Jonathan,如果你想匹配,那么所有的数值您可以使用htmlContent.match(/\d+/g)

1

要报废来自URL的数字就像从任何字符串中抽取数字一样,只要您的链接遵循每次都具有相同格式的一般规则:意味着只有一个数字。也许你会遇到港口问题。

这就是说你需要提取网址:window.location.pathname,所以你只会得到URL中“http://example.com:8080”之后的内容。 urlString.match('[\\d]+');

例如:: 然后用正则表达式解析URL串

function getUrlId(){ 
    var path = window.location.pathname; 
    var result = path.match('[\\d]+'); 
    return result[0]; 
}; 
相关问题