Soner
Soner

Reputation: 3

Get a specific string of numbers inside an url

So here we have some url's from same domain:

http://example.com/video6757788/sometext 
http://example.com/video24353/someothertext  
http://example.com/video243537786/somedifferenttext  
http://example.com/video759882  
http://example.com/video64353415  
http://example.com/video342432?session=somestring 

How to get just the numbers part that comes after video in all types of the url's. I'm trying to get the video id's.

First i get the url's, but then how do I get the id's?

var url = $('a[href*="example"]');
var id = ???

Upvotes: 0

Views: 304

Answers (1)

megawac
megawac

Reputation: 11353

Use a regular expression:

$('a[href*="example"]').each(function() {
   var $this = $(this);
   var url = $this.attr("href");
   var id = url.match(/video(\d+)/i)[1]; //retrieve the number following video*
   //logic
})

Or if you want to be fancy with .attr(), equivalent would be:

 $('a[href*="example"]').attr("href", function(indx, url) {
   var id = url.match(/video(\d+)/i)[1]; //retrieve the number following video*
   //logic
})

Upvotes: 2

Related Questions