0

url: http://xxxxxx.com/video/view/12345

Can I take 12345 in the url using javascript?

Please help me

3 Answers3

1

Use RegExp, Array#match and negative lookahead.

var str = 'http://xxxxxx.com/video/view/12345';
    console.log(str.match(/(?!view\/)\d+/)[0]);
kind user
  • 40,029
  • 7
  • 67
  • 77
  • Duplicates all around. Perhaps find one and close? – mplungjan Mar 21 '17 at 16:11
  • 1
    @mplungjan There's no exact the same solution as mine, in the link you have provided. Also it's much easier than the methods mentioned there. – kind user Mar 21 '17 at 16:13
  • You mean this is harder? `window.location.href.split('/').pop()` - also you assume there is a view always - the duplicate just takes the last – mplungjan Mar 21 '17 at 16:14
  • @mplungjan Fine, but your solution will work only if that number is the last element in the url. – kind user Mar 21 '17 at 16:15
  • And yours only works if view is one but last - more versions here to play with http://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript – mplungjan Mar 21 '17 at 16:16
  • @mplungjan Yes, it will work only if there's a `view` word preceding the number. But since it's a static url, coming from some video site, it will work without any problems. Seems like only this number at the end is dynamic. – kind user Mar 21 '17 at 16:17
  • If that is so, then `var num = str.split('/').pop()` is certainly simpler than a regex – mplungjan Mar 21 '17 at 16:22
  • @mplungjan But what if the site passes some params in url? Like `view/12345?cookies=true`. – kind user Mar 21 '17 at 16:23
  • `location.pathname.split('/').pop()` – mplungjan Mar 21 '17 at 16:42
0

You can parse your URL with the following code. Then just get the last part.

var url = 'http://xxxxxx.com/video/view/12345';
var url_parts = url.replace(/\/\s*$/,'').split('/');
console.log(url_parts[url_parts.length - 1]); // last part
Mistalis
  • 17,793
  • 13
  • 73
  • 97
0

You can also try this if you're sure that it'll always be in last:

var num = location.pathname.split('/').pop(); // "12345"

and further: parseInt(num);

mehulmpt
  • 15,861
  • 12
  • 48
  • 88