I have
var id="ctl03_Tabs1";
Using JavaScript, how might I get the last five characters or last character?
To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string. Copied! const str = 'Hello World'; const last3 = str.
string str = "AM0122200204"; string substr = str. Substring(str. Length - 3);
To get the last two characters of a string, call the slice() method, passing it -2 as a parameter. The slice method will return a new string containing the last two characters of the original 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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With