2

How to check if last character of a string is a digit/number in plain 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');
}

Also I would like to know what would be the most fastest way? I guess it may sound ridiculous :D but in my usecase I will need this method very often so I think it could make a difference.

bensiu-acc
  • 92
  • 8
RE666
  • 91
  • 1
  • 9
  • @str, my bad totally forgot about "NaN". So then, `var str = "R2D2"; -> isNaN(str[str.length - 1]) === false && typeof +str[str.lenght - 1] === "number;` – Krusader Dec 01 '19 at 09:31

2 Answers2

6

You can use 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'));
Mamun
  • 66,969
  • 9
  • 47
  • 59
1
function endsWithNumber( str: string ): boolean {

    return str && str.length > 0 && str.charAt( str.length - 1 ).match( /[0-9A-Za-z]/ );
}
Dai
  • 141,631
  • 28
  • 261
  • 374