Munkhdelger Tumenbayar
Munkhdelger Tumenbayar

Reputation: 1874

Getting last character of variable?

I tried to get the last character of a variable. 'var' is getting q1d from that select.

I want to get d in qwer var. Maybe its duplicated question but I am asking why those doesn't work ?

> slice, substr, split ?

      var qwer=$('.chkbox[value="' + $('#tablebody tr:last td:last-child').text() + '"]').attr("id");
      alert(qwer);// alerting q1d
      qwer.slice(-1); // i tried slice, substr, split but all same 
      alert(qwer);// alerting still q1d

Upvotes: 3

Views: 1816

Answers (7)

Dario
Dario

Reputation: 6280

Try passing -1 to substr; if a negative parameter is passed it is treated as strLength - parameter where strLength is the length of the string (see here):

qwer.substr(-1)

Upvotes: -1

X.Nane
X.Nane

Reputation: 44

alert(qwer.slice(-1));

or

qwer = qwer.slice(-1);alert(qwer);

Upvotes: 1

guradio
guradio

Reputation: 15555

  1. use .split() - make array of letters
  2. use .pop() - get last element of array of letters

var qwer = "q1d";

alert(qwer.split('').pop())

Upvotes: 0

prasanth
prasanth

Reputation: 22490

you are missing to declare the variable of slice result .slice not affect the original variable its just returning .so you need re declare the result value of slice otherwise its call the first declared result only

qwer = 'qId'
qwer = qwer.slice(-1);
console.log(qwer);

Upvotes: 4

user7110739
user7110739

Reputation:

var qwer = "qId";
var lastChar = qwer.substr(qwer.length - 1); // => "d"
console.log(lastChar);

Upvotes: 1

Dij
Dij

Reputation: 9808

you can just use the bracket notation to get the last character.

qwer = 'qId'
qwer = qwer[qwer.length-1];
console.log(qwer);

Upvotes: 4

Robby Cornelissen
Robby Cornelissen

Reputation: 97130

Because strings are immutable in JavaScript, none of the functions you mention modify the string in-place. You need to assign the result of the operation back to a variable:

let qwer = 'q1d';
qwer = qwer.slice(-1);

console.log(qwer);

Upvotes: 2

Related Questions