admin管理员组

文章数量:1353245

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

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
Share Improve this question edited Aug 10, 2017 at 7:52 Munkhdelger Tumenbayar asked Aug 10, 2017 at 7:46 Munkhdelger TumenbayarMunkhdelger Tumenbayar 1,88419 silver badges30 bronze badges 1
  • add html mark up as well – guradio Commented Aug 10, 2017 at 7:47
Add a ment  | 

7 Answers 7

Reset to default 4

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

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

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

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

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

or

qwer = qwer.slice(-1);alert(qwer);
  1. use .split() - make array of letters
  2. use .pop() - get last element of array of letters

var qwer = "q1d";

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

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)

本文标签: javascriptGetting last character of variableStack Overflow