Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get last characters of a string

Tags:

javascript

I have

var id="ctl03_Tabs1"; 

Using JavaScript, how might I get the last five characters or last character?

like image 232
user695663 Avatar asked May 03 '11 18:05

user695663


People also ask

How do I get the last 5 characters of a string?

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.

How do I print the last 3 characters of a string?

string str = "AM0122200204"; string substr = str. Substring(str. Length - 3);

How do I get the last two characters of a string?

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.


1 Answers

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).

like image 58
Jamon Holmgren Avatar answered Oct 07 '22 08:10

Jamon Holmgren