Question

I'm making a pretty basic Chrome extension that I use primarily for personal use and use between friends. In any case, I essentially have a URL that looks like this:

i.imgur.com/abcd123.png or imgur.com/a2b3c78 or even i.imgur.com/herp321.png?1

The only thing I need out of these URLs are the 7 character codes prior to the extension. In these examples, abcd123, a2b3c78, and herp321.

I've been running a .replace that won't catch exceptions like the third example, and even attempting to throw some regex at it (Which I haven't been able to get even close to functioning properly). The only part of the URL that is constant is as follows, with the code marked as x:

imgur.com/xxxxxxxx

The URL may have a varying beginning, and a varying end immediately after the 7-digit code, but the above is constant. Is there a way of pulling only this alphanumeric filename from the above example, regardless of what prefaces the URL or any modifiers/extensions added to the end?

Was it helpful?

Solution

matched=str.match(/imgur.com\/(.{7})/);
//matched[1] will have your result

OTHER TIPS

A simple aproach:

 var text   = 'i.imgur.com/herp321.png?1'
 var regex  = /imgur\.com\/(\w{7})/;

 console.log(text.match(regex)[1]);

You can try this:

/.+\/([a-z0-9]+).+/

in JS:

var imgUrl = 'i.imgur.com/dsf8635235.png?sdgdsgdsg'
  , matches = imgUrl.match( /.+\/([a-z0-9]+).+/ );

console.log( matches[ 1 ] ); // dsf8635235

Some variations:

console.log( 'imgur.com/dsf8635235'.match( /.+\/([a-z0-9]+).+/ )[ 1 ] ); // dsf8635235
console.log( 'i.imgur.com/dsf8635235'.match( /.+\/([a-z0-9]+).+/ )[ 1 ] ); // dsf8635235
console.log( 'imgur.com/dsf8635235?1'.match( /.+\/([a-z0-9]+).+/ )[ 1 ] ); // dsf8635235

etc.

You can use the match function with an regex expression for that.

EDIT:

This should work:

var urls = ["i.imgur.com/abcd123.png", "imgur.com/a2b3c78", "i.imgur.com/herp321.png?1"];
var reg =  /\/(.{7})/;

for(i=0;i<urls.length;i++) {
  reg.exec(urls[i]);
  console.log(RegExp.$1);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top