繁体   English   中英

如何使用javascript获取网址的特定部分?

[英]How to get a specific portion of the url using javascript?

var url = window.location.href.toString();

上一行为我正确显示了当前页面的网址,我的网址是:

http://localhost/xyzCart/products.php?cat_id=35

但是,使用javascript我如何才能只获取一部分网址,即从上面的网址中我只想要

products.php?cat_id=35

如何完成这个plz帮助。我在这个论坛上已经看过类似的问题,但是对我没有任何帮助。

您可以使用以下方法:

var url = window.location.href.toString();
var newString = url.substr(url.lastIndexOf(".") + 1));

这将导致:php?cat_id = 35祝你好运/ Zorken17

尝试以下Javacript代码以获取所需的部分。 它用“ /”分隔您的网址,并占用第四部分。 在描述清晰度方面,这优于substr解决方案。

url.split("/")[4]

或者,如果url可以包含更多“ /”路径部分,则只需采用最后分割的部分。

var parts = url.split("/");
console.log( parts[parts.length-1] );

您可以使用最终的/的位置:

var page = url.substr(url.substr(0, (url + "?").indexOf("?")).lastIndexOf("/") + 1);

(这允许/在查询字符串中)

您可以使用javascript split()方法获得所需的结果。 检查此链接以获取更多详细信息

https://jsfiddle.net/x06ywtvo/

var urls = [
    "http://localhost/xyzCart/products.php?cat_id=35",
    "http://localhost/xyzCart/products.php",
    "http://www.google.com/xyzCart/products.php?cat_id=37"
];

var target = $('#target');
for(var i=0;i<urls.length;i++){
    var index = urls[i].indexOf("xyzCart");
    var sub = urls[i].substring(index, urls[i].length);
    target.append("<div>" + sub + "</div>");
}

您将在window.location对象中获得所有必需的值。 请检查以下CodePen Link是否正确输出。

我添加了参数test=1链接: http : //codepen.io/rajesh_dixit/pen/EVebJe? test=1

 (function() { var url = window.location.pathname.split('/'); var index = 1; document.write("URL: "); document.write(window.location.href); document.write("<br/> Full Path: "); document.write(window.location.pathname); document.write("<br/> Last Value:") // For cases where '/' comes at the end if(!url[url.length - index]) index++; document.write(url[url.length-index]) document.write("<br/> Query Parameter: "); document.write(window.location.search.substring(1)); })() 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM