最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

extract - Getting ID from URL using JavaScript - Stack Overflow

programmeradmin3浏览0评论

I`m new to JavaScript and I need some help extracting the ID from URL using JavaScript for a gallery.

This is the link: www.shinylook.ro/produs/44/mocasini-barbati.html.

I need that number 44 in a variable.

I`m new to JavaScript and I need some help extracting the ID from URL using JavaScript for a gallery.

This is the link: www.shinylook.ro/produs/44/mocasini-barbati.html.

I need that number 44 in a variable.

Share Improve this question edited Jun 26, 2012 at 15:06 pimvdb 155k80 gold badges311 silver badges356 bronze badges asked Jun 26, 2012 at 14:57 user1483138user1483138 671 gold badge1 silver badge7 bronze badges 7
  • 1 Welcome to Stack Overflow! What have you tried? – Matt Ball Commented Jun 26, 2012 at 14:59
  • 1 possible duplicate of Get ID from URL with jQuery – Esailija Commented Jun 26, 2012 at 14:59
  • 1 @Esailija: Except this isn't flagged with jquery, and the number isn't at the end of the URL. Many of the answers there rely on one or the other of those. – T.J. Crowder Commented Jun 26, 2012 at 15:04
  • 1 @Esailija: No, I'm not: This answer is precisely useless if the OP isn't using jQuery, just as the accepted answer is useless for this questioner (as it relies on the number being the last thing in the URL). – T.J. Crowder Commented Jun 26, 2012 at 15:13
  • 1 @Esailija: We just disagree. :-) (I didn't call it a "crime" -- that would have been way overstating it if I had.) – T.J. Crowder Commented Jun 26, 2012 at 16:21
 |  Show 2 more comments

2 Answers 2

Reset to default 12

You have to use the location object to get the URL, after that, you can use split to split the URL on the slashes.

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

You can do that with String#split or with a regular expression.

String#split lets you split a string on a delimiter and get an array as a result. So in your case, you could split on / and get an array where 44 would be at index 2.

Regular expressions let you do much more complicated matching and extraction, as shown by the various demos on the linked page. For instance,

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)
}

In both cases, the number will be a string. You can parse it with parseInt, e.g. n = parseInt(s, 10) (assuming it's base 10).

发布评论

评论列表(0)

  1. 暂无评论