admin管理员组文章数量:1135023
My url will look like this:
How can I get the word "action". This last part of the url (after the last forward slash "/") will be different each time. So whether its "action" or "adventure", etc. how can I always get the word after the last closing forward slash?
My url will look like this:
http://www.example.com/category/action
How can I get the word "action". This last part of the url (after the last forward slash "/") will be different each time. So whether its "action" or "adventure", etc. how can I always get the word after the last closing forward slash?
Share Improve this question edited May 29, 2011 at 1:24 Ateş Göral 140k27 gold badges141 silver badges191 bronze badges asked May 29, 2011 at 1:22 JacobJacob 7131 gold badge5 silver badges4 bronze badges 1- related stackoverflow.com/questions/8376525/… – Adriano Commented Aug 5, 2013 at 7:47
6 Answers
Reset to default 203One way:
var lastPart = url.split("/").pop();
Assuming there is no trailing slash, you could get it like this:
var url = "http://www.mysite.com/category/action";
var parts = url.split("/");
alert(parts[parts.length-1]);
However, if there can be a trailing slash, you could use the following:
var url = "http://www.mysite.com/category/action/";
var parts = url.split("/");
if (parts[parts.length-1].length==0){
alert(parts[parts.length-2]);
}else{
alert(parts[parts.length-1]);
}
str.substring(str.lastIndexOf("/") + 1)
Though if your URL could contain a query or fragment, you might want to do
var end = str.lastIndexOf("#");
if (end >= 0) { str = str.substring(0, end); }
end = str.lastIndexOf("?");
if (end >= 0) { str = str.substring(0, end); }
first to make sure you have a URL with the path at the end.
Or the regex way:
var lastPart = url.replace(/.*\//, ""); //tested in FF 3
OR
var lastPart = url.match(/[^/]*$/)[0]; //tested in FF 3
Check out the split method, it does what you want: http://www.w3schools.com/jsref/jsref_split.asp
Well, the first thing I can think of is using the split
function.
string.split(separator, limit)
Since everyone suggested the split function, a second way wood be this:
var c = "http://www.example.com/category/action";
var l = c.match(/\w+/g)
alert(l)
The regexp is just a stub to get the idea. Basically you get every words in the url.
l = http,www,example,com,category,action
get the last one.
本文标签: How to get the last part of a string in JavaScriptStack Overflow
版权声明:本文标题:How to get the last part of a string in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736913628a1956219.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论