[英]I want to split the window url with javascript
I have a URL like this: 我有这样的网址:
http://www.exemple.local/en/node/28
I want to split only the en
part and insert it in another div. 我只想分割
en
部分并将其插入另一个div中。 My code is something like this: 我的代码是这样的:
var url = window.location.href;
var urlDomaine = document.location.origin
var splitedUrl = url.split(urlDomaine)[1];
console.log(splitedUrl);
$('.div').text(splitedUrl);
This will print to me the /en/node/28
and I don't want to split it again, any ideas? 这将向我显示
/en/node/28
,我不想再次拆分,有什么想法吗?
You don't need to hack the string around with split()
, or any other convoluted methods. 您不需要使用
split()
或任何其他复杂的方法修改字符串。
Simply use window.location.pathname
. 只需使用
window.location.pathname
。 When run on the URL you've specified this will return: 在您指定的网址上运行时,将返回:
/en/node/28
If you only want the en
value, split the pathName
then retrieve the second element of the resulting array: 如果只需要
en
值,请分割pathName
然后检索结果数组的第二个元素:
var pathName = window.location.pathName; // = '/en/node/28'
var lang = pathName.split('/')[1]; // = 'en'
Here's how you can use ES6 destructuring feature to break down your full url into it's various parts: 您可以使用以下方式使用ES6解构功能将完整的url分解为各个部分:
var path = 'http://www.exemple.local/en/node/28' let [protocol, url, locale, node, id] = path.split('/').filter(chunk => chunk.length); console.log(protocol); console.log(url); console.log(locale); console.log(node); console.log(id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.