admin管理员组文章数量:1310126
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');
}
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.
Share Improve this question edited May 1, 2021 at 6:11 bensiu-acc 928 bronze badges asked Dec 1, 2019 at 9:20 RE666RE666 911 silver badge9 bronze badges 1-
@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 Commented Dec 1, 2019 at 9:31
2 Answers
Reset to default 7You can use Conditional (ternary) operator with isNaN()
and 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(''));
function endsWithNumber( str: string ): boolean {
return str && str.length > 0 && str.charAt( str.length - 1 ).match( /[0-9A-Za-z]/ );
}
本文标签:
版权声明:本文标题:How to check if last character of a string is a digitnumber by the fastest way in plain JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741800483a2398189.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论