Posted in Code Snippets, Javascript

Get filename from URL with extension

Get the filename from the URL or path using Javascript:

Consider the URL:

var url = "http://www.example.com/my_page.html"

Method 1:

url.split('/').pop()

Method 2: Regular Expression

url.replace(/^.*[\\\/]/, '')

Both method returns

my_page.html


But when URL is something like this with query parameters:

var url = "http://www.example.com/my_page.html?id=123&value=456"

Then above methods will return:

my_page.html?id=123&value=456

In order to remove query parameters from the URL, use:

url.split('/').pop().split('?')[0]

This again returns

​​​​my_page.html

Query parameters reside in next index.

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s