1017

I have

var id="ctl03_Tabs1";

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

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
user695663
  • 11,856
  • 8
  • 26
  • 32

25 Answers25

1390

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

Jamon Holmgren
  • 23,738
  • 6
  • 59
  • 75
  • 7
    The first solution can be made shorter and faster, see my answer below. However, I do agree with the split and pop idea in this particular situation. – Terence Mar 18 '13 at 09:45
  • Awesome, I was checking if there was a "last" or "right" method in js, or if I had to use substr and length - I would not have thought of split/pop either. :) – neminem Dec 20 '13 at 16:15
  • fyi, if you need a certain number of characters, the first method is more than 10 times faster than the pop method in my tests. I do like the elegance of the second method and it certainly has it's place. – sday Jan 18 '14 at 13:32
  • 6
    [Compared](http://jsperf.com/get-last-chars) to .slice(-5) and .substr(length - 5), `.split().pop()` is a big performance hit. If this is something you're using in a loop and performance is critical, you'll want to keep this in mind. – nwayve Feb 17 '14 at 16:07
  • 12
    In your test, `.split().pop()` is still 5 million operations per second. It's not a performance problem until it's a performance problem. ;) – Jamon Holmgren Feb 17 '14 at 18:27
  • `id.substr(id.length - 1) === id.substr(-1)` – chharvey Mar 05 '15 at 05:01
  • `.substr` [should not be used in new code](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr). In addition, `.slice` accepts negative indices, without needing to use the string length manually, so no reason not to use it. – Hutch Moore Oct 24 '18 at 16:13
  • 4
    @HutchMoore You are correct. I've edited my answer to mention that `slice` is a better option at this point. – Jamon Holmgren Oct 29 '18 at 22:01
  • 1
    If you're trying to apply `slice` or `substr` on a number (int), convert it to string first. E.g. `myVar.toString().slice(-5)` – dnns Jul 19 '19 at 10:04
  • 6
    If you're here because you wanted to retrieve the extension of a filename, then `filename.split(".").pop()` is significantly smarter than slicing with a negative value of 3. Alot of these answers mention using negative values, but what happens when `Tabs12` comes along and you're getting `abs12` as a result. The `.split("_").pop()` solution posted here is again, significantly smarter than anyone saying that slice should be used – zanderwar Oct 03 '19 at 01:44
  • **Better `slice`**. As `String.prototype.substr(…)` is not strictly deprecated (as in "removed from the Web standards"), it is considered a **legacy function** and should be avoided when possible. It is not part of the core JavaScript language and may be removed in the future. If at all possible, use the substring() method instead. - From [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr) – Ajeet Shah May 30 '20 at 21:52
1012

Don't use the deprecated .substr()!

Use either the .slice() method because it is cross browser compatible (see issue with IE). Or use the .substring() method.

The are slight differences in requirements, which are properly documented on: String.prototype.substring()

const id = "ctl03_Tabs1";

console.log(id.slice(-5)); //Outputs: Tabs1
console.log(id.slice(-1)); //Outputs: 1

// below is slower
console.log(id.substring(id.length - 5)); //Outputs: Tabs1
console.log(id.substring(id.length - 1)); //Outputs: 1
Terence
  • 10,533
  • 1
  • 14
  • 20
  • 12
    Yes slice accept negative values which is great ! `slice()` reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice – Offirmo Oct 30 '13 at 09:19
  • 5
    I prefer this answer, though the accepted one works just fine. – Dave Watts Nov 16 '13 at 12:39
  • 7
    This should be the answer, using slice this way is also more performant: https://jsperf.com/slice-vs-substr-and-length – theVinchi Oct 20 '16 at 15:49
  • Chrome 55 seems to think substr is 20% faster – fantapop Nov 07 '16 at 06:15
  • 8
    I assume slice will only work if its consistent? what if the end was `_Tabs15` ? slice(-5) would only grab `abs15` ? split/pop works far better for varied lengths... – Brian Ramsey Jan 25 '17 at 09:37
  • @BrianRamsey what would you grab if `-Tabs5` with split/pop ? – Bekim Bacaj Nov 16 '17 at 18:36
  • Sorry, but how is id.slide(id.length-5) more efficient than id.substr(-5) . What if you wanted to grab the word 'Tabs' only with slice? With substr you can do id.substr(-5,4). How does slice do that efficiently with out you then having to learn a new function to do it? – Watts Epherson Oct 03 '19 at 12:56
  • @BrianRamsey Maybe this... id.substr(id.indexOf("Tabs")) – Watts Epherson Oct 03 '19 at 13:02
  • JavaScript does not only run in a browser. Use whatever fits your needs. – DreamWave Jul 23 '20 at 10:43
  • This not works if the length of the text is smaller than the n las characters. With id.slice(-5) works fine in both cases – Hanzo Apr 26 '22 at 10:04
134

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);
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
user682701
  • 1,441
  • 1
  • 9
  • 4
  • 4
    Best and short answer. No need to know the original string length (for current browsers, so we exclude IE) – Thanh Trung Apr 23 '20 at 07:03
  • 3
    This is by far the best and shortest way to achieve the result – Alpha Jul 18 '20 at 20:40
  • This sounds good, but does not always work, see here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_substring4 – Roger Perkins Sep 16 '21 at 16:01
  • @RogerPerkins Why are you posting an example with substring when this post is about substr?? – Daniele Testa Sep 17 '21 at 06:14
  • I get confused as to which language uses which substring command, looks like javascript can use either one though, although it looks like only substr works properly for negative numbers. Looks like even w3schools is confused to the operation of substr, stating for negative number:
    If start is negative, substr() uses it as a character index from the end of the string.
    If start is negative or larger than the length of the string, start is set to 0
    – Roger Perkins Sep 17 '21 at 23:30
72

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.

Zirak
  • 38,920
  • 13
  • 81
  • 92
34

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

Community
  • 1
  • 1
tamil
  • 361
  • 3
  • 2
29
const r = '6176958e92d42422203a3c58'; 
r.slice(-4)

results '3c58'

r.slice(-1)

results '8'

Zoe
  • 27,060
  • 21
  • 118
  • 148
user769371
  • 295
  • 3
  • 10
  • 1
    Slice has already been recommended multiple times, but with far more explanation. Notably, this doesn’t offer anything new compared to [this highly voted answer](https://stackoverflow.com/a/15473635/3025856). Please don’t repeat existing guidance, and especially with less explanation. – Jeremy Caney Oct 30 '21 at 17:54
15

One way would be using slice, like follow:

var id="ctl03_Tabs1";
var temp=id.slice(-5);

so the value of temp would be "Tabs1".

Keivan
  • 1,300
  • 1
  • 16
  • 29
12

Check out the substring function.

To get the last character:

id.substring(id.length - 1, id.length);
Chewpers
  • 2,430
  • 5
  • 23
  • 30
10

The Substr function allows you to use a minus to get the last character.

var string = "hello";
var last = string.substr(-1);

It's very flexible. For example:

// Get 2 characters, 1 character from end
// The first part says how many characters
// to go back and the second says how many
// to go forward. If you don't say how many
// to go forward it will include everything
var string = "hello!";
var lasttwo = string.substr(-3,2);
// = "lo"
Watts Epherson
  • 692
  • 5
  • 9
9

Performance

Today 2020.12.31 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v84 for chosen solutions for getting last N characters case (last letter case result, for clarity I present in separate answer).

Results

For all browsers

  • solution D based on slice is fast or fastest
  • solution G is slowest

enter image description here

Details

I perform 2 tests cases:

  • when string has 10 chars - you can run it HERE
  • when string has 1M chars - you can run it HERE

Below snippet presents solutions A B C D E F G (my)

//https://stackoverflow.com/questions/5873810/how-can-i-get-last-characters-of-a-string

// https://stackoverflow.com/a/30916653/860099
function A(s,n) {
  return s.substr(-n)
}

// https://stackoverflow.com/a/5873890/860099
function B(s,n) {
  return s.substr(s.length - n)
}

// https://stackoverflow.com/a/17489443/860099
function C(s,n) {
  return s.substring(s.length - n, s.length);
}

// https://stackoverflow.com/a/50395190/860099
function D(s,n) {
  return s.slice(-n);
}

// https://stackoverflow.com/a/50374396/860099
function E(s,n) {
  let i = s.length-n;
  let r = '';
  while(i<s.length) r += s.charAt(i++);
  return r
}

// https://stackoverflow.com/a/17489443/860099
function F(s,n) {
  let i = s.length-n;
  let r = '';
  while(i<s.length) r += s[i++];
  return r
}

// my
function G(s,n) {
  return s.match(new RegExp(".{"+n+"}$"));
}

// --------------------
// TEST
// --------------------

[A,B,C,D,E,F,G].map(f=> {  
  console.log(
    f.name + ' ' + f('ctl03_Tabs1',5)
  )})
This shippet only presents functions used in performance tests - it not perform tests itself!

And here are example results for chrome

enter image description here

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
8

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"
Nello Ollen
  • 327
  • 6
  • 22
6
const id = 'ctl03_Tabs1';
id.at(-1); // Returns '1'

at supports negative integer to count back from the last string character.


Docs: String/at

t_dom93
  • 10,226
  • 1
  • 52
  • 38
5

If you just want the last character or any character at know position you can simply trat string as an array! - strings are iteratorable in javascript -

Var x = "hello_world";
 x[0];                    //h
 x[x.length-1];   //d

Yet if you need more than just one character then use splice is effective

x.slice(-5);      //world

Regarding your example

"rating_element-<?php echo $id?>"

To extract id you can easily use split + pop

Id= inputId.split('rating_element-')[1];

This will return the id, or undefined if no id was after 'rating_element' :)

Zalaboza
  • 8,899
  • 16
  • 77
  • 142
5

Performance

Today 2020.12.31 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v84 for chosen solutions for getting last character case (last N letters case results, for clarity I present in separate answer).

Results

For all browsers

  • solutions D,E,F are quite-fast or fastest
  • solutions G,H are slowest

enter image description here

Details

I perform 2 tests cases:

  • when string has 10 chars - you can run it HERE
  • when string has 1M chars - you can run it HERE

Below snippet presents solutions A B C D E F G (my), H (my)

//https://stackoverflow.com/questions/5873810/how-can-i-get-last-characters-of-a-string

// https://stackoverflow.com/a/30916653/860099
function A(s) {
  return s.substr(-1)
}

// https://stackoverflow.com/a/5873890/860099
function B(s) {
  return s.substr(s.length - 1)
}

// https://stackoverflow.com/a/17489443/860099
function C(s) {
  return s.substring(s.length - 1, s.length);
}

// https://stackoverflow.com/a/50395190/860099
function D(s) {
  return s.slice(-1);
}

// https://stackoverflow.com/a/50374396/860099
function E(s) {  
  return s.charAt(s.length-1);
}

// https://stackoverflow.com/a/17489443/860099
function F(s) {  
  return s[s.length-1];
}

// my
function G(s) {
  return s.match(/.$/);
}

// my
function H(s) {
  return [...s].pop();
}

// --------------------
// TEST
// --------------------

[A,B,C,D,E,F,G,H].map(f=> {  
  console.log(
    f.name + ' ' + f('ctl03_Tabs1')
  )})
This shippet only presents functions used in performance tests - it not perform tests itself!

And here are example results for chrome

enter image description here

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
4

const id = "ctl03_Tabs1";

console.log(id.slice(-5)); //Outputs: Tabs1
console.log(id.slice(0,4)); //Outputs: ctl0

 
Ankit saxena
  • 81
  • 1
  • 10
3
var id="ctl03_Tabs1";
var res = id.charAt(id.length-1);

I found this question and through some research I found this to be the easiest way to get the last character.

As others have mentioned and added for completeness to get the last 5:

var last5 = id.substr(-5);
Andrew Mallonee
  • 364
  • 1
  • 11
3

You can exploit the string.length feature to get the last characters. See the below example:

let str = "hello";
console.log(str[str.length-1]);
// Output : 'o' i.e. Last character.

Similarly, you can use for loops to reverse the string using the above code.

arbob
  • 239
  • 2
  • 6
2

Assuming you will compare the substring against the end of another string and use the result as a boolean you may extend the String class to accomplish this:

String.prototype.endsWith = function (substring) {
  if(substring.length > this.length) return false;
  return this.substr(this.length - substring.length) === substring;
};

Allowing you to do the following:

var aSentenceToPonder = "This sentence ends with toad"; 
var frogString = "frog";
var toadString = "toad";
aSentenceToPonder.endsWith(frogString) // false
aSentenceToPonder.endsWith(toadString) // true
mikeborgh
  • 1,192
  • 11
  • 22
  • You've now got code that redefines [the built in `endsWith` method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith)... Just kidding, that's the `startsWith` method. But it goes to show that you should always test for existing methods before defining your own on built-in objects. And probably stay away from built-in methods altogether, like lodash and underscore. – Heretic Monkey Sep 02 '21 at 11:44
2

To get the last character of a string, you can use the split('').pop() function.

const myText = "The last character is J";
const lastCharater = myText.split('').pop();
console.log(lastCharater); // J

It's works because when the split('') function has empty('') as parameter, then each character of the string is changed to an element of an array. Thereby we can use the pop() function which returns the last element of that array, which is, the 'J' character.

Arghya Sadhu
  • 41,002
  • 9
  • 78
  • 107
Jonas Braga
  • 379
  • 4
  • 5
1

I actually have the following problem and this how i solved it by the help of above answer but different approach in extracting id form a an input element.

I have attached input filed with an

id="rating_element-<?php echo $id?>"

And , when that button clicked i want to extract the id(which is the number) or the php ID ($id) only.

So here what i do .

 $('.rating').on('rating.change', function() {
            alert($(this).val());
           // console.log(this.id);
           var static_id_text=("rating_element-").length;       
           var product_id =  this.id.slice(static_id_text);       //get the length in order to deduct from the whole string    
          console.log(product_id );//outputs the last id appended
        });
Develop4Life
  • 7,581
  • 8
  • 58
  • 76
0

This one will remove the comma if it is the last character in the string..

var str = $("#ControlId").val();

if(str.substring(str.length-1)==',') {

  var stringWithoutLastComma = str.substring(0,str.length-1);    

}
Code Lღver
  • 15,573
  • 16
  • 56
  • 75
vijay yaragall
  • 111
  • 2
  • 12
0

Last 5

var id="ctl03_Tabs1";
var res = id.charAt(id.length-5)
alert(res);

Last

   
 var id="ctl03_Tabs1";
 var res = id.charAt(id.length-1)
alert(res);
Rajkumar
  • 1,017
  • 9
  • 12
0

you can use slice

id.slice(-5);

-1

I am sure this will work....

var string1="myfile.pdf"
var esxtenion=string1.substr(string1.length-4)

The value of extension will be ".pdf"

Jamil Moughal
  • 19
  • 1
  • 6
-1

Here 2 examples that will show you always the last character

var id="ctl03_Tabs1";

console.log(id.charAt(id.length - 1)); 

console.log(id[id.length - 1]);