如何在 JavaScript 中获取字符串的最后一部分?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6165381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:31:01  来源:igfitidea点击:

How to get the last part of a string in JavaScript?

javascript

提问by Jacob

My url will look like this:

我的网址将如下所示:

http://www.example.com/category/action

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?

我怎么能得到“行动”这个词。url 的最后一部分(在最后一个正斜杠“/”之后)每次都会不同。那么无论是“动作”还是“冒险”等,我怎样才能在最后一个关闭正斜杠之后得到这个词?

回答by Ates Goral

One way:

单程:

var lastPart = url.split("/").pop();

回答by Niklas

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 canbe 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]);  
}

回答by Mike Samuel

str.substring(str.lastIndexOf("/") + 1)

Though if your URL could contain a query or fragment, you might want to do

虽然如果您的 URL 可以包含查询或片段,您可能想要做

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.

首先确保你有一个带有路径的 URL。

回答by dierre

Well, the first thing I can think of is using the splitfunction.

好吧,我能想到的第一件事就是使用该split功能。

string.split(separator, limit)

Since everyone suggested the split function, a second way wood be this:

由于每个人都建议使用 split 函数,第二种方式木材是这样的:

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

l = http,www,example,com,category,action

get the last one.

得到最后一个。

回答by Jonathon

Or the regex way:

或正则表达式方式:

var lastPart = url.replace(/.*\//, ""); //tested in FF 3

OR

或者

var lastPart = url.match(/[^/]*$/)[0]; //tested in FF 3

回答by pfhayes

Check out the split method, it does what you want: http://www.w3schools.com/jsref/jsref_split.asp

查看 split 方法,它可以满足您的需求:http: //www.w3schools.com/jsref/jsref_split.asp