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?

3
  • 2
    Seems like something you should be handling server side. Commented Aug 20, 2014 at 5:38
  • 1
    you can try changing window.location.href, but after changing it might not work, this should be on server side. Commented Aug 20, 2014 at 5:38
  • stackoverflow.com/questions/6478485/… Commented Aug 20, 2014 at 5:40

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
but now we can't reload the page.
1

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

Comments

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]

Comments

0

Try this using Jquery :-

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.