How do I remove or change the .html extension in my url using javascript or jQuery?

My html page url is www.example.com/training/product.html. I want to change my url as www.example.com/training/product. Can I use javascript or JQuery? How?

+3


source to share


4 answers


Sorry I cannot comment due to reputation limitation.

The correct solution is not yet available in the comments.

window.history.replaceState()

      

performs the task.

I would do:



var link = 'www.example.com/training/product.html';
link.split('.html')[0];
window.history.replaceState( null, null, link );

      

For a more respected solution, go to How to reliably get the filename without suffix in javascript?

Link

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_replaceState().C2.A0method

+4


source


Using javascript

, you can achieve it like this:

var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
if (a.indexOf('html') > -1) { //Check of html String in URL.
   url = url.substring(0, newURL.lastIndexOf("."));
}

      



If you are looking at server level changes, below are the rules for the .htaccess file

RewriteEngine On

# remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://example.com/folder/$1 [R=301,L]

# Redirect external .html requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.html([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.html$ http://example.com/folder/$1 [R=301,L]

# Resolve .html file for extensionless html urls
RewriteRule ^([^/.]+)$ $1.html[L]

      

+1


source


Try using JQuery: -

var url = "www.example.com/training/product.html";
url = url.substring(0, url.lastIndexOf("."));

      

0


source


You can do this with MVC. It cannot be done with Javascript. This needs to be done on the server side.

0


source







All Articles