如何以最快的方式检查字符串的最后一个字符是否为 digit/number JavaScript?

How to check if last character of a string is a digit/number by the fastest way in plain JavaScript?

如何在普通 JavaScript 中检查字符串的最后一个字符是否为 digit/number?

function endsWithNumber(str){
  return str.endsWith(); // HOW TO CHECK IF STRING ENDS WITH DIGIT/NUMBER ???
}

var str_1 = 'Pocahontas';
var str_2 = 'R2D2';

if (endsWithNumber(str_1)) {
  console.log(str_1 + 'ends with a number');
} else {
  console.log(str_1 + 'does NOT end with a number');
}

if (endsWithNumber(str_2)) {
  console.log(str_2 + 'ends with a number');
} else {
  console.log(str_2 + 'does NOT end with a number');
}

另外我想知道最快的方法是什么?我想这听起来可能很荒谬 :D 但在我的用例中我会经常需要这种方法所以我认为它可能会有所作为。

function endsWithNumber( str: string ): boolean {

    return str && str.length > 0 && str.charAt( str.length - 1 ).match( /[0-9A-Za-z]/ );
}

您可以使用 Conditional (ternary) operator with isNaN() and String.prototype.slice():

function endsWithNumber( str ){
  return isNaN(str.slice(-1)) ? 'does NOT end with a number' : 'ends with a number';
}

console.log(endsWithNumber('Pocahontas'));
console.log(endsWithNumber('R2D2'));