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

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

问题描述

我有

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).

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

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