KOMPX.COM or COMPMISCELLANEA.COM   

Get the name of a web page (JavaScript)

Getting the name of a web page, when it has:

There may be a query string or not, an anchor or not.

HTML code:


<div class="example"></div>

JavaScript code:


<script>
var current_page_pathname = window.location.pathname;
var current_page_pathname_arrayed = current_page_pathname.split('/');
var current_page_pathname_last_character = current_page_pathname.slice( -1 );
var current_page_url_name = '';

// There is an extension or no extension and no slash at the end
if ( current_page_pathname_last_character !== '/' ) {
	current_page_url_name = current_page_pathname.split('/').pop();
	/// Printing the result
	document.querySelector('.example').textContent = current_page_url_name;
}

// There is a slash at the end, but still there is a pathname content
if ( current_page_pathname_last_character == '/' && current_page_pathname !== '/' ) {
	current_page_url_name = current_page_pathname_arrayed[ current_page_pathname_arrayed.length - 2 ];
	/// Printing the result
	document.querySelector('.example').textContent = current_page_url_name;
}

// There is no pathname content, just the default prefixing slash. Like at homepage or search results page
if ( current_page_pathname == '/' ) {
	current_page_url_name = 'Empty';
	/// Printing the result
	document.querySelector('.example').textContent = current_page_url_name;
}
</script>

Links

  1. How can I get the name of an html page in Javascript? stackoverflow.com/questions/16611497/how-can-i-get-the-name-of-an-html-page-in-javascript
  2. Location: pathname property developer.mozilla.org/en-US/docs/Web/API/Location/pathname
  3. Array.prototype.slice() developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
  4. Array.prototype.pop() developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop
Browser support
Windows
Edge 12.0+
Firefox 3.5+
Google Chrome 1.0+
Opera 12.1+
Linux
Firefox 3.5+
Google Chrome 1.0+
Opera 12.1+
iOS
Safari 2.0+
Android
Samsung Internet 1.0+
Chrome 18.0+
Firefox 4.0+
Opera 12.1+
More