snippetjavascriptCritical
How can I get last characters of a string
Viewed 0 times
lasthowcharacterscanstringget
Problem
I have
Using JavaScript, how might I get the last five characters or last character?
var id="ctl03_Tabs1";Using JavaScript, how might I get the last five characters or last character?
Solution
EDIT: As others have pointed out, use
Original answer:
You'll want to use the Javascript string method
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.
You can also use the
If you're simply looking to find the characters after the underscore, you could use this:
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).
slice(-5) instead of substr. However, see the .split().pop() solution at the bottom of this answer for another approach.Original answer:
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"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.
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).
Code Snippets
var id = "ctl03_Tabs1";
var lastFive = id.substr(id.length - 5); // => "Tabs1"
var lastChar = id.substr(id.length - 1); // => "1"var tabId = id.split("_").pop(); // => "Tabs1"Context
Stack Overflow Q#5873810, score: 1427
Revisions (0)
No revisions yet.