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).
const id = "ctl03_Tabs1"; console.log(id.slice(id.length - 5)); //Outputs: Tabs1 console.log(id.slice(id.length - 1)); //Outputs: 1
Read more... Read less...
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.
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
There is no need to use
substr method to get a single char of a string!
taking the example of Jamon Holmgren we can change substr method and simply specify the array position:
var id = "ctl03_Tabs1"; var lastChar = id[id.length - 1]; // => "1"