-1

I need a way to get the extension out of any absolute url you might have.

Out of all these things i want to see mp4 as output. I want a regEx to do it. Please help me and explain what your expression means, or point me in the riht direction.

Nicky Smits
  • 2,980
  • 4
  • 20
  • 27
  • possible duplicate of [Parse URL with jquery/ javascript?](http://stackoverflow.com/questions/6644654/parse-url-with-jquery-javascript) – TimWolla Mar 27 '14 at 02:09
  • Just a heads up, "extension" is meaningless in HTTP URLs; Content-type overrides pretty much everything. – David Ehrmann Mar 27 '14 at 03:57
  • @DavidEhrmann Thats right. But i want to both get videos by content-type, and secondly i want to find m3u8 files. ;) – Nicky Smits Mar 27 '14 at 04:31

3 Answers3

2

Note that this is a dicey business. You can almost always find an input to break your pattern. However, if you're confident about the range of the inputs, something simple may suffice.

This pattern will put the extension into group 1:

\.([^/#?]+)([#?][^/]*)?$

Tests:

rex = new RegExp('\\.([^/#?]+)([#?][^/]*)?$');

rex.test('http://example.com/lol.mp4')
console.log(RegExp.$1)
// prints "mp4"

rex.test('http://example.com/lol.mp4?test')
console.log(RegExp.$1)
// prints "mp4"

rex.test('http://example.com/lol.mp4#test')
console.log(RegExp.$1)
// prints "mp4"

Explanation

\.            # Match a period (note backslash is doubled in string literal)
(
 [^/#?]+      # Match a positive number of non-delimiters (path, hash, or query)
)             # save that to group 1
(             # also,
  [#?]        # Match the start of an anchor or query
  [^/]*       # and as many non path-delimiters that follow
)?            # maybe
$             # oh, and only at the end of the input
harpo
  • 41,820
  • 13
  • 96
  • 131
  • 1
    @NickySmits, I think I misunderstood. Your question title says find "fileName", while the text of your question says "extension". Since you didn't give the desired output, or define "didn't work", we're hitting the limit of how much people can help you. – harpo Mar 27 '14 at 02:58
  • I edited the title. However, come on, my description was retty clear, i specifically asked for the extension multiple times – Nicky Smits Mar 27 '14 at 03:09
-1

This worked like a charm.

string.split('.').pop().match(/\w+/)[0];

If there is a dot after ? or #, the following will work:

string.split(/\?|#/)[0].split('.').pop().match(/\w+/)[0];
Nicky Smits
  • 2,980
  • 4
  • 20
  • 27
-1

using

/\.mp4/igm 

regular expression it select all mp4 as out put

  • So basically. Your expression returns mp4 no matter what? Thats really not useful. If the extension was a constant i wouldnt tey to find it – Nicky Smits Mar 27 '14 at 03:34