使用JavaScript获取字符串中的最后一个数字

编写一个示例代码来获取JavaScript中字符串中的最后一个数字。

您可以通过在 'match' 中使用带有正则表达式的 '+$' 来获得它。

如果最后一个字符不是数字,则代码不起作用。

获取最后的数字

在“match”中使用正则表达式获取字符串中最后的数值。

let strNum = 'AAA_01'

console.log( Number(strNum.match(/\d+$/)[0]) ) ; // 1

strNum = '11_AAA_10'

console.log( Number(strNum.match(/\d+$/)[0]) ) ; // 10

strNum = '11_AAA010'

console.log( Number(strNum.match(/\d+$/)[0]) ) ; // 10

如果不使用“Number”进行数值化,例如下列中"AAA_01"获取结果为"01"。

let strNum = 'AAA_01'

console.log( (strNum.match(/\d+$/)[0]) ) ; // 01

strNum = '11_AAA_10'

console.log( (strNum.match(/\d+$/)[0]) ) ; // 10

strNum = '11_AAA010'

console.log( (strNum.match(/\d+$/)[0]) ) ; // 010

如果您只想获取最后一位数,请删除表示继续的“+”。

let strNum = 'AAA_01'

console.log( (strNum.match(/\d$/)[0]) ) ; // 1

strNum = '11_AAA_10'

console.log( (strNum.match(/\d$/)[0]) ) ; // 0

strNum = '11_AAA010'

console.log( (strNum.match(/\d$/)[0]) ) ; // 0

使用JavaScript获取字符串中的最后一个数字

不以数字结尾

如果最后一个不是数字,则为错误。

let strNum = '111AAA'

console.log( (strNum.match(/\d+$/)[0]) ) ; 
// Uncaught TypeError: Cannot read properties of null (reading '0')

为了避免这个错误,让我们添加一个条件表达式,要求最后一个字符串是一个数字,并将其包装成一个函数。

function getLastNum(str){

 // 判断是否为数字
  if(Number.isFinite(Number(str.slice(-1)))) return Number(str.match(/\d+$/)[0]);

  return '';

}

console.log( getLastNum('AAA1') ); // 1
console.log( getLastNum('AAA12') ); // 12
console.log( getLastNum('AAA012') ); // 12
console.log( getLastNum('AAA') ); // 
console.log( getLastNum('123') ); // 123


本文来源:词雅网

本文地址:https://www.ciyawang.com/javascript-getlastnum.html

本文使用「 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 」许可协议授权,转载或使用请署名并注明出处。

相关推荐