如何使用javascript更改url中的语言代码
我正在开发一个网站,在两种语言的工作,我需要改变网址,包括选定的网址 我真正需要的是 1-选择当前url 2-检查是否包含任何语言代码 3-如果不存在,则追加代码;如果存在,则将代码更改为所选代码 例如:如何使用javascript更改url中的语言代码,javascript,Javascript,我正在开发一个网站,在两种语言的工作,我需要改变网址,包括选定的网址 我真正需要的是 1-选择当前url 2-检查是否包含任何语言代码 3-如果不存在,则追加代码;如果存在,则将代码更改为所选代码 例如: http://localhost:11767/Home/resultMain?model=1&&type=1 上面的链接使用英语,因为它是默认语言,当用户单击es语言时,它应该是默认语言 http://localhost:11767/es/Home/resultMain?mo
http://localhost:11767/Home/resultMain?model=1&&type=1
上面的链接使用英语,因为它是默认语言,当用户单击es语言时,它应该是默认语言
http://localhost:11767/es/Home/resultMain?model=1&&type=1
我不知道这是否就是你想要的。但JavaScript可以使用对象“位置”获取URL。尤其是
location.pathname
对您很有用。您可以在location.pathname
上应用reg exp来检查URL是否包含/es/
,如果是,则通过适当的Ajax请求将网站翻译到后端
但通常我建议使用后端的路由。我认为最好的解决方案是使用http头通知服务器首选语言
您可以在a元素的帮助下解析URL,然后替换所需的部分并重新构建URL: 函数addReplaceLangCode(url,langCode){ var a=document.createElement('a'); a、 href=document.getElementById('url').value;//或document.location.href; var path=a.pathname.split('/'); path.shift(); if(路径[0]。长度==2){ 路径[0]=langCode; }否则{ 路径.取消移位(langCode); } 返回a.protocol+'/'+ a、 主机+“/”+路径。连接(“/”)+ (a.搜索!=“a.搜索:”)+ (a.hash!=“a.hash:”); } 函数onClickReplace(){ document.getElementById('result').innerHTML=addReplaceLangCode(document.location.href,'es'); }
URL:
结果:
根据@Bulnet Vural上面的回答,我编写了以下代码,因为我需要在url中切换语言路径
var getOtherLanguageLocation = function (currentUrl, languagePath) {
// based on https://stackoverflow.com/a/42176588/1378980
var anchorTag = document.createElement('a');
anchorTag.href = currentUrl;
var paths = anchorTag.pathname.split("/");
// remove all the empty items so we don't get double slash when joining later.
var paths = paths.filter(function (e) { return e !== '' })
// the language will be at index 1 of the paths
if (paths.length > 0 && paths[0].toLowerCase() == languagePath) {
// remove the language prefix
paths.splice(0, 1);
} else {
// add the language prefix
paths.unshift(languagePath);
}
return anchorTag.protocol + '//' +
anchorTag.host + '/' + paths.join('/') +
anchorTag.search + anchorTag.hash;
};
您的后端是用哪种语言编写的?你使用的是node js吗?@Daniel ASP.NET MVCChange window.location?如果url是,此方法将消除部分查询字符串参数,用户单击英文链接将非常感谢它现在工作正常,你真的节省了我的时间:)此代码中的小错误当url是,我再次单击时,它将导致再次单击注意问号前的斜杠。请现在检查。我们不必在查询字符串和哈希之前添加额外的“/”。