How can I get last characters of a string

How can I get last characters of a string

I have
var id=”ctl03_Tabs1″;

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

Solutions/Answers:

Solution 1:

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

Solution 2:

Don’t use .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

substr() with negative value not working in IE

Solution 3:

Getting the last character is easy, as you can treat strings as an array:

var lastChar = id[id.length - 1];

To get a section of a string, you can use the substr function or the substring function:

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 substr and 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.

Solution 4:

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

Solution 5:

Following script shows the result for get last 5 characters and last 1 character in a string using JavaScript:

var testword='ctl03_Tabs1';
var last5=testword.substr(-5); //Get 5 characters
var last1=testword.substr(-1); //Get 1 character

Output :

Tabs1 // Got 5 characters

1 // Got 1 character

Solution 6:

Check out the substring function.

To get the last character:

id.substring(id.length - 1, id.length);