Get last 4 digits of string javascript

I have

var id="ctl03_Tabs1";

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

Uwe Keim

38.7k56 gold badges173 silver badges282 bronze badges

asked May 3, 2011 at 18:12

3

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

answered May 3, 2011 at 18:19

Jamon HolmgrenJamon Holmgren

22.8k6 gold badges57 silver badges75 bronze badges

11

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

answered Mar 18, 2013 at 9:41

TerenceTerence

9,8151 gold badge14 silver badges20 bronze badges

10

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

Get last 4 digits of string javascript

Mogsdad

43.4k20 gold badges147 silver badges263 bronze badges

answered Jun 18, 2015 at 13:25

user682701user682701

1,4011 gold badge9 silver badges4 bronze badges

5

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.

answered May 3, 2011 at 18:21

ZirakZirak

37.9k12 gold badges78 silver badges90 bronze badges

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

answered Apr 18, 2012 at 4:52

tamiltamil

3413 silver badges2 bronze badges

1

const r = '6176958e92d42422203a3c58'; 
r.slice(-4)

results '3c58'

r.slice(-1)

results '8'

Get last 4 digits of string javascript

answered Oct 30, 2021 at 8:51

user769371user769371

2773 silver badges9 bronze badges

1

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

answered May 17, 2018 at 15:26

Get last 4 digits of string javascript

KeivanKeivan

1,0541 gold badge14 silver badges26 bronze badges

Check out the substring function.

To get the last character:

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

answered May 3, 2011 at 18:15

Get last 4 digits of string javascript

ChewpersChewpers

2,4024 gold badges22 silver badges30 bronze badges

0

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"

answered Apr 1, 2019 at 11:08

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"

answered Jul 5, 2013 at 12:55

Get last 4 digits of string javascript

Nello OllenNello Ollen

3275 silver badges22 bronze badges

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

Get last 4 digits of string javascript

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)

And here are example results for chrome

Get last 4 digits of string javascript

answered Dec 31, 2020 at 0:18

Get last 4 digits of string javascript

Kamil KiełczewskiKamil Kiełczewski

75.7k26 gold badges335 silver badges311 bronze badges

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

answered Nov 17, 2017 at 22:47

ZalabozaZalaboza

8,73916 gold badges75 silver badges136 bronze badges

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

Get last 4 digits of string javascript

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)

And here are example results for chrome

Get last 4 digits of string javascript

answered Dec 31, 2020 at 0:11

Get last 4 digits of string javascript

Kamil KiełczewskiKamil Kiełczewski

75.7k26 gold badges335 silver badges311 bronze badges

const id = 'ctl03_Tabs1';
id.at(-1); // Returns '1'

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


Docs: String/at

answered Mar 21, 2021 at 17:37

Get last 4 digits of string javascript

t_dom93t_dom93

8,4821 gold badge46 silver badges34 bronze badges

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

answered May 16, 2018 at 15:07

Get last 4 digits of string javascript

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.

answered Apr 11, 2021 at 13:44

Get last 4 digits of string javascript

arbobarbob

1511 silver badge5 bronze badges

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

answered Jan 24, 2016 at 0:51

mikeborghmikeborgh

1,18411 silver badges21 bronze badges

1

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.

Get last 4 digits of string javascript

Arghya Sadhu

37k9 gold badges67 silver badges91 bronze badges

answered Aug 22, 2020 at 14:38

Get last 4 digits of string javascript

Jonas BragaJonas Braga

1313 silver badges3 bronze badges

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

answered Jun 8, 2015 at 10:34

Get last 4 digits of string javascript

Daniel AdenewDaniel Adenew

7,3237 gold badges54 silver badges75 bronze badges

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

}

Get last 4 digits of string javascript

Code Lღver

15.5k16 gold badges54 silver badges74 bronze badges

answered Aug 30, 2013 at 6:00

1

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

answered Apr 1, 2019 at 11:16

rajmobiapprajmobiapp

9298 silver badges10 bronze badges

1

you can use slice

id.slice(-5);

answered May 10 at 9:17

Get last 4 digits of string javascript

I am sure this will work....

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

The value of extension will be ".pdf"

answered Sep 4, 2018 at 15:05

Get last 4 digits of string javascript

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

answered Sep 17, 2020 at 16:03

How do I find the last 4 digits of a string?

If data is in not in string form, use String..
String lastFourDigits = "" ; //substring containing last 4 characters..
if (input.length() > 4 ) {.
lastFourDigits = input.substring(input.length() - 4 ); }.
else. {.
lastFourDigits = input; }.
System. out. println(lastFourDigits);.

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 you find the last digit of a string?

Method 1: Using String..
The idea is to use charAt() method of String class to find the first and last character in a string..
The charAt() method accepts a parameter as an index of the character to be returned..

How do I get the last character in a JavaScript string?

To get the last character of a string, call the charAt() method on the string, passing it the last index as a parameter. For example, str. charAt(str. length - 1) returns a new string containing the last character of the string.