在JavaScript中最后一个斜杠后获取字符串的值 [英] Get value of a string after last slash in JavaScript

查看:137
本文介绍了在JavaScript中最后一个斜杠后获取字符串的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了一个多小时,并且想不出正确的方法,尽管这可能很简单:

I am already trying for over an hour and cant figure out the right way to do it, although it is probably pretty easy:

我有这样的东西:foo/bar/test.html

我想使用jQuery提取最后一个/之后的所有内容.在上面的示例中,输出为test.html.

I would like to use jQuery to extract everything after the last /. In the example above the output would be test.html.

我想可以使用substrindexOf()完成此操作,但是我找不到可行的解决方案.

I guess it can be done using substr and indexOf(), but I cant find a working solution.

推荐答案

至少三种方式:

var result = /[^/]*$/.exec("foo/bar/test.html")[0];

...在字符串($)的末尾显示获取不包含斜杠的一系列字符"([^/]*).然后,它通过索引到匹配对象中来检索匹配的字符([0]);在匹配对象中,第一个条目是整个匹配的字符串.无需捕获组.

...which says "grab the series of characters not containing a slash" ([^/]*) at the end of the string ($). Then it grabs the matched characters from the returned match object by indexing into it ([0]); in a match object, the first entry is the whole matched string. No need for capture groups.

实时示例

var str = "foo/bar/test.html";
var n = str.lastIndexOf('/');
var result = str.substring(n + 1);

lastIndexOf 听起来像是:找到索引最后出现在字符串中的字符(井,字符串)的次数,如果未找到则返回-1.在十分之九的时间中,您可能想检查该返回值(if (n !== -1)),但是在上面的代码中,由于我们要向其添加1并调用子字符串,因此最终会执行str.substring(0),而该结果仅返回字符串.

lastIndexOf does what it sounds like it does: It finds the index of the last occurrence of a character (well, string) in a string, returning -1 if not found. Nine times out of ten you probably want to check that return value (if (n !== -1)), but in the above since we're adding 1 to it and calling substring, we'd end up doing str.substring(0) which just returns the string.

Sudhir和Tom Walters在此处

Sudhir and Tom Walters have this covered here and here, but just for completeness:

var parts = "foo/bar/test.html".split("/");
var result = parts[parts.length - 1]; // Or parts.pop();

split使用给定的分隔符分割字符串,并返回一个数组.

split splits up a string using the given delimiter, returning an array.

lastIndexOf/substring解决方案是可能效率最高的(尽管人们总是要谨慎地讲讲JavaScript和性能,因为各个引擎之间的差异很大),但是除非您要循环执行数千次,否则不要紧,我会尽力使代码更清晰.

The lastIndexOf / substring solution is probably the most efficient (although one always has to be careful saying anything about JavaScript and performance, since the engines vary so radically from each other), but unless you're doing this thousands of times in a loop, it doesn't matter and I'd strive for clarity of code.

这篇关于在JavaScript中最后一个斜杠后获取字符串的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆