Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

javascript - 如何获取字符串的最后一个字符(How can I get last characters of a string)

I have

(我有)

var id="ctl03_Tabs1";

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

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

  ask by user695663 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

EDIT: As others have pointed out, use slice(-5) instead of substr .

(编辑:正如其他人指出的那样,使用slice(-5)代替substr)

However, see the .split().pop() solution at the bottom of this answer for another approach.

(但是,请参阅此答案底部的.split().pop()解决方案,以了解另一种方法。)

Original answer:

(原始答案:)

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

(您需要结合使用Javascript字符串方法.substr().length属性。)

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

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.

(这将获取从id.length-5开始的字符,并且由于省略了.substr()的第二个参数,因此将继续到字符串的末尾。)

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

(您还可以使用.slice()方法,如下面其他人指出的那样。)

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

(这会将字符串分割为下划线的一个数组,然后将弹出的最后一个元素“弹出”该数组(即您想要的字符串)。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...