How To Extract The Filename Of The Url Of The Current Document Path In Javascript?
Solution 1:
If you're looking for the last item in the path, try this:
var current_path = window.location.pathname.split('/').pop();
This:
window.location.pathname
will give you something like:
"/questions/6543242/how-to-extract-the-filename-of-url-in-javascript"
Then the .split()
will split the string into an Array, and .pop()
will give you the last item in the Array.
Solution 2:
functionfilename(path){
path = path.substring(path.lastIndexOf("/")+ 1);
return (path.match(/[^.]+(\.[^?#]+)?/) || [])[0];
}
console.log(filename('http://example.com/index.html?lang=ja'));
// returned value: 'index.html'
Solution 3:
The filename of a URL is everything following the last "/"
up to one of the following: 1.) a "?"
(beginning of URL query), or 2.) a "#"
(beginning of URL fragment), or 3.) the end of the string (if there is no query or fragment).
This tested regex does the trick:
.match(/[^\/?#]+(?=$|[?#])/);
Solution 4:
There is a URL.js library that makes it very easy to work with URLs. I recommend it!
Example
var uri = new URI('http://example.org/foo/hello.html?foo=bar');
uri.filename(); // => 'hello.html'
Solution 5:
your regex isn't correct. Instead try to be more specific:
.match(/([a-zA-Z\-\_0-9]+\.[a-zA-Z]{2,4})[\?\$]/);
says:
find any number of alphanumeric or hypens[a-zA-Z\-\_0-9]+
before a fullstop that has between 2 and 4 alphabetic characters [a-zA-Z]{2,4}
that combefore either the end (\$
) or a question mark (\?
)
tested on:
("http://www.example.com/index.html?lang=ja").match(/([a-zA-Z\-\_0-9]+\.[a-zA-Z]{2,4})[\?\$]/);
var current_path = RegExp.$1;
alert(current_path);
Post a Comment for "How To Extract The Filename Of The Url Of The Current Document Path In Javascript?"