获取字符串中的最后一个字符

时间:2020-03-24 12:09:58

标签: angular

我有一个字符串值,例如5d,并且需要获取最后一个字符d。字符串可以是5d2d或仅仅是e,等等。

我尝试了以下操作,但得到了5

const timeLeft = this.myData[contentIndex].timeLeft;
const lastChar = timeLeft.substring(0, timeLeft.length - 1);

我要去哪里错了?

2 个答案:

答案 0 :(得分:0)

使用slice()方法和length属性

var str = '5d';
console.log(str.slice(str.length - 1))

var str = '3d';
console.log(str.slice(str.length - 1))

var str = 'e';
console.log(str.slice(str.length - 1))

答案 1 :(得分:0)

按照下面的代码。在js中非常简单。

const timeLeft = this.myData[contentIndex].timeLeft;
const lastChar = timeLeft[timeLeft.length - 1];
相关问题