How can I get last characters of a string
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.
.substr() combined with the
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).
.substr(). Use the
.slice() method instead because it is cross browser compatible (see IE).
var id = "ctl03_Tabs1"; id.slice(-5); //Outputs: Tabs1 id.slice(-1); //Outputs: 1
Getting the last character is easy, as you can treat strings as an array:
var lastChar = id[id.length - 1];
id.substr(id.length - 1); //get the last character id.substr(2); //get the characters from the 3rd character on id.substr(2, 1); //get the 3rd character id.substr(2, 2); //get the 3rd and 4th characters
The difference between
substring is how the second (optional) parameter is treated. In
substr, it’s the amount of characters from the index (the first parameter). In
substring, it’s the index of where the character slicing should end.
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);
var testword='ctl03_Tabs1'; var last5=testword.substr(-5); //Get 5 characters var last1=testword.substr(-1); //Get 1 character
Tabs1 // Got 5 characters
1 // Got 1 character
Check out the substring function.
To get the last character:
id.substring(id.length - 1, id.length);