如何在纯 JavaScript 中以最快的方式检查字符串的最后一个字符是否是数字/数字?

RE6*_*666 2 javascript string ends-with

如何在纯 JavaScript 中检查字符串的最后一个字符是否是数字/数字?

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');
}
Run Code Online (Sandbox Code Playgroud)

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

Mam*_*mun 6

您可以将条件(三元)运算isNaN()符与String.prototype.slice()一起使用:

function endsWithNumber(str){
  str = str.trim();
  if (!str) return 'Invalid input'; //return if input is empty
  return isNaN(str.slice(-1)) ? 'does NOT end with a number' : 'ends with a number';
}

console.log(endsWithNumber('Pocahontas'));
console.log(endsWithNumber('R2D2'));
console.log(endsWithNumber(''));
Run Code Online (Sandbox Code Playgroud)