How can I get last characters of a string
You can use the substr() method with a negative starting position to retrieve the last n characters. For example, this gets the last 5:
var lastFiveChars = id.substr(-5);
EDIT: 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.
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).
Don't use the deprecated .substr()
!
Use either the .slice()
method because it is cross browser compatible (see issue with IE).
Or use the .substring()
method.
The are slight differences in requirements, which are properly documented on: String.prototype.substring()
const id = "ctl03_Tabs1";
console.log(id.slice(-5)); //Outputs: Tabs1
console.log(id.slice(-1)); //Outputs: 1
// below is slower
console.log(id.substring(id.length - 5)); //Outputs: Tabs1
console.log(id.substring(id.length - 1)); //Outputs: 1