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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25397372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:28:08  来源:igfitidea点击:

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

javascriptjqueryhtml

提问by sanman

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?

我的 html 页面 url 是www.example.com/training/product.html。我想将我的网址更改为www.example.com/training/product。是否可以使用 javascript 或 Jquery?如何?

回答by user32342534

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?

要获得更受尊重的解决方案,请转到如何在 javascript 中可靠地获取没有后缀的文件名?

Link:

关联:

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

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

回答by Chandan

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

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

回答by Vivek Pratap Singh

Using javascriptyou can achieve this like:

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

If you are looking at Server level changes, Below are the rules for .htaccess file

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

RewriteEngine On

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

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

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

回答by Kartikeya Khosla

Try this using Jquery :-

使用 Jquery 试试这个:-

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