4

My html page url is www.example.com/training/product.html. I want to change my url like to www.example.com/training/product. Is it possible using javascript or Jquery? How?

sanman
  • 770
  • 1
  • 7
  • 15

4 Answers4

7

Sorry I can not comment due to Reputation-Restriction.

The right solution is not yet in the comments.

window.history.replaceState()

does the job.

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 the suffix in javascript?

Link:

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

Community
  • 1
  • 1
user32342534
  • 145
  • 6
  • 3
    No need to make this a comment, this is the correct answer (with a documentation link even), plus now you're only 1 pt away from the comment priv. For browser compatibility (IE mainly has issues with this solution) there's also a solution which uses the hash (`#`) at the end of the URL to manipulate the text. – nbrooks Aug 20 '14 at 06:05
  • but now we can't reload the page. – douglas Dec 29 '22 at 02:48
1

You can do that by using MVC. This can not be done by Javascript. This needs to be done on server side.

ivarni
  • 17,658
  • 17
  • 76
  • 92
Chandan
  • 11
  • 1
  • 7
1

Using javascript you can achieve this like:

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 .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]
Vivek Pratap Singh
  • 9,326
  • 5
  • 21
  • 34
0

Try this using Jquery :-

var url = "www.example.com/training/product.html";
url = url.substring(0, url.lastIndexOf("."));
Kartikeya Khosla
  • 18,743
  • 8
  • 43
  • 69