如何使用JavaScript获取字符串的最后一个字符 [英] How can I get last characters of a string using JavaScript

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

问题描述

我有

var id="ctl03_Tabs1";

使用JavaScript,我如何获得最后五个字符或最后一个字符?

Using JavaScript, how might I get the last five characters or last character?

推荐答案

编辑:正如其他人所指出的那样,使用 slice(-5)代替 substr 然而,请参阅底部的 .split()。pop()解决方案另一种方法的答案。

As others have pointed out, use slice(-5) instead of substr. However, see the .split().pop() solution at the bottom of this answer for another approach.

原始答案:

你想要的使用Javascript字符串方法 .substr()结合 .length 属性。

You'll want to use the Javascript string method .substr() combined with the .length property.

var id = "ctl03_Tabs1";
var lastFive = id.substr(id.length - 5); // => "Tabs1"
var lastChar = id.substr(id.length - 1); // => "1"

这将获得从id.length开始的字符 - 5,因为第二个参数为省略.substr(),继续到字符串的结尾。

This gets the characters starting at id.length - 5 and, since the second argument for .substr() is omitted, continues to the end of the string.

你也可以使用 .slice()其他人在下面指出的方法。

You can also use the .slice() method as others have pointed out below.

如果您只是想在下划线后找到字符,可以使用:

If you're simply looking to find the characters after the underscore, you could use this:

var tabId = id.split("_").pop(); // => "Tabs1"

这会将字符串拆分为下划线上的数组,然后弹出最后一个元素关闭数组(这是你想要的字符串)。

This splits the string into an array on the underscore and then "pops" the last element off the array (which is the string you want).

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

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