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

查看:513
本文介绍了在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提取最后一个<$ c后的所有内容$ C> / 。在上面的示例中,输出将是 test.html

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

我想可以使用<$ c来完成$ c> substr 和 indexOf(),但我找不到可行的解决方案。

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 执行它听起来的样子:它找到 last 出现的索引字符串中的字符(井,字符串),如果找不到则返回-1。十分之九,你可能想要检查返回值( if(n!== -1)),但是在上面我们为它添加1并且调用substring,我们最终会做 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天全站免登陆