如何从URL中仅提取数值,使用Javascript或jQuery实现。

4

需要提取包含数字值的URL。但是数字值的位置在URL中不是固定的。需要一种通用的方法来提取。不能使用split方法,因为值的位置不是固定的。

例如:

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具有数字值,其位置不固定。 你能否提供一种通用方法,使我可以获得期望的输出结果,如“1234567”。

5个回答

7

使用基本的正则表达式:

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

这将返回字符串中的第一组数字。在上面的例子中,我们得到了以下结果:

[ "1234567" ]

0

这里有一个fiddle

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

请注意,这意味着网址中没有其他数字序列!一点都没有!

0

又一个工作正常的 :)

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


0
从URL中提取数字就像从任何字符串中提取数字一样,只要你的链接遵循每次都有相同格式的通用规则:也就是说只有一个数字。也许您会遇到端口的问题。
话虽如此,您需要提取URL:window.location.pathname,这样您就只能得到URL中“http://example.com:8080”后面的内容。 然后使用正则表达式解析URL字符串:urlString.match('[\\d]+'); 例如:
function getUrlId(){
  var path  = window.location.pathname;
  var result = path.match('[\\d]+');
  return result[0];   
};

0

补充@Jonathan,如果你想匹配所有数字值,那么可以使用htmlContent.match(/\d+/g)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接