title: Get filename from URL using Regular Expressions or Javascript
body: <p>I need to get the filename from the URL address.</p>
  
  <p>Here is the criteria:</p>
  
  <p>It need to return empty string <code>""</code> in following scenarios:</p>
  
  <pre><code>http://somedomain.com
  http://www.somedomain.com
  http://somedomain.com/
  http://www.somedomain.com/
  </code></pre>
  
  <p>And return filename.php in the following scenarios:</p>
  
  <pre><code>http://somedomain.com/filename.php?query
  http://www.somedomain.com/filename.php?query
  http://somedomain.com/filename.php#query
  http://www.somedomain.com/filename.php#query
  </code></pre>
  
  <p>I found this regular expression</p>
  
  <p><code>[\w_.-]*?(?=[\?\#])|[\w_.-]*$</code> from <a href="http://www.pagecolumn.com/tool/url_regex.htm" rel="noreferrer">here</a></p>
  
  <p>however it returns <code>somedomain.com</code> on input <code>http://somedomain.com</code>. I can't figure out how to modify it to ignore the domain when there is no <code>/</code> at the end of it.</p>
  
  <p>If it is difficult to do with regular expressions, I will appreciate a JavaScript solution as well.</p>
  
  <p>Thanx in advance.</p>