2012-06-26 27 views
2

我是JavaScript新手,我需要一些帮助从URL中使用JavaScript为图库中提取ID。使用JavaScript从URL获取ID

这是链接:www.shinylook.ro/produs/44/mocasini-barbati.html

我需要在变量中的数字44。

+1

欢迎来到Stack Overflow! [你有什么尝试?](http://whathaveyoutried.com) –

+1

可能的重复[从jQuery获取URL的URL](http://stackoverflow.com/questions/3730359/get-id-from-url-with -jquery) – Esailija

+1

@Esailija:除了不用'jquery'标记,并且该数字不在URL的末尾。那里的许多答案都依赖于其中的一个。 –

回答

8

您必须使用location对象才能获取URL,之后,您可以使用split来将URL拆分为斜线。

location.pathname.split('/')[2] // Returns 44 in your example 
+0

这是我对这种链接 http://www.shinylook.ro/product.php?id=44 function transferair(){ \t var v = {}; \t var foo = window.location.href.replace(/ [?&] +([^ =&] +)=([^&] *)/ gi,函数(m,cheie,val)\t \t v [cheie] = val; \t \t}); \t return v; } – user1483138

+0

对于这个例子,你可以使用这个'location.search.replace('?id =','')[1]' – Calvein

+0

谢谢,我做到了! – user1483138

3

你可以用String#splitregular expression来做到这一点。

String#split可让您在分隔符上拆分字符串并获取数组。所以在你的情况下,你可以拆分/并得到一个数组,其中44将在索引2处。

正则表达式可让您执行更复杂的匹配和提取,如链接页面上的各种演示所示。例如,

var str = "www.shinylook.ro/produs/44/mocasini-barbati.html"; 
var m = /produs\/(\d+)\//.exec(str); 
if (m) { 
    // m[1] has the number (as a string) 
} 

在这两种情况下,数字都是字符串。你可以用parseInt来解析它,例如n = parseInt(s, 10)(假设它是基数10)。

+0

请您详细说明这个'm [1]'后卫是干什么的?我认为'+'量词是多余的。 – pimvdb

+0

@pimvdb:的确如此,谢谢。卫生署!我确实倾向于是一个腰带和大括号的人,但那是OTT。 :-) –