[javascript] 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?

This question is related to javascript

The answer is


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

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

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)

_x000D_
_x000D_
//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)
  )})
_x000D_
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
_x000D_
_x000D_

And here are example results for chrome

enter image description here


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

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.


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

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)

_x000D_
_x000D_
//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')
  )})
_x000D_
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
_x000D_
_x000D_

And here are example results for chrome

enter image description here


Last 5

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

Last

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


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"

I am sure this will work....

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

The value of extension will be ".pdf"


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.


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"

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


Here 2 examples that will show you always the last character

_x000D_
_x000D_
var id="ctl03_Tabs1";

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

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


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

}

Don't use .substr(). Use the .slice() method instead because it is cross browser compatible (see IE).

_x000D_
_x000D_
const id = "ctl03_Tabs1";_x000D_
console.log(id.slice(id.length - 5)); //Outputs: Tabs1_x000D_
console.log(id.slice(id.length - 1)); //Outputs: 1
_x000D_
_x000D_
_x000D_

substr() with negative value not working in IE


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


Check out the substring function.

To get the last character:

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

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' :)