如何删除或更改.html扩展在我的url使用javascript或jQuery

How to remove or change .html extension in my url using javascript or jQuery?

本文关键字:扩展 我的 url jQuery javascript 使用 html 何删除 删除      更新时间:2023-09-26

我的html页面url是www.example.com/training/product.html.我想改变我的url喜欢www.example.com/training/product.是否可能使用javascript或Jquery?如何?

抱歉,由于声誉限制,我不能评论。

正确的解决方案还没有在评论中。

window.history.replaceState()

起作用

我会这样做:

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

对于一个更受尊重的解决方案去如何可靠地获得文件名没有javascript后缀?

<标题>链接:

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

您可以通过使用MVC来做到这一点。这是Javascript无法做到的。这需要在服务器端完成。

使用javascript,您可以这样实现:

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("."));
}

如果您正在查看服务器级别的更改,下面是.htaccess文件

的规则
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]

尝试使用Jquery:-

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