简体   繁体   English

用javascript或jQuery解析URL

[英]parsing url with javascript or jquery

I have a url in this form http://www.example.com/data/45 . 我有一个网址,格式为http://www.example.com/data/45 How do I get the last element (45 in this example) using jQuery or JavaScript? 如何使用jQuery或JavaScript获取最后一个元素(在此示例中为45)?

Thanks. 谢谢。

A very quick plain JavaScript method, assuming it's the URL of the current page (in window.location.href ) 一种非常快速的普通JavaScript方法,假设它是当前页面的URL(在window.location.href

var urlNum = window.location.href.split('/').pop();

.split('/') obviously chops the URL up into an array, based on divisions by / . .split('/')显然砍下URL成一个阵列,基于由分割/ Since you only need the last part, it is probably the easiest method. 由于只需要最后一部分,因此它可能是最简单的方法。

.pop() removes the last element from the array returned by .split() and returns it. .pop().split()返回的数组中删除最后一个元素,并将其返回。

var num = 'http://www.example.com/data/45'.split('/').pop(); //num now == '45'

My rendition :) 我的演义:)

var url         = 'http://www.example.com/data/45';
var lastSegment = url.substr(url.lastIndexOf('/') + 1);

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

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