就像标题说的那样 示例说明: x)示例字符串->我需要作为输出
示例:
1) "asdf" -> null or -1 or undefined (because nothing was found)
2) "asdf1" -> 1
3) "asdf0" -> 0
4) "asdf-1" -> 1
5) "asdf001" -> 1
6) "asdf1234" -> 1234
7) "asdf12.34" -> 34 (ending value, so number after .)
8) "123asdf78" -> 78 (integer from ending)
我希望这些例子足够了。我尝试使用for循环执行此操作,但没有成功。有谁知道是否有可以执行类似或类似操作的功能?
有关我的方法的更多信息: 在for循环中,我检查每个字符是否> ='0'&& <='9',然后将其添加到负责串联所有字符的先前tmp变量中,最后将其解析为int。但我认为这种解决方案很糟糕...
答案 0 :(得分:2)
您可以为此使用简单的正则表达式:
function numericSuffix(string) {
const match = string.match(/\d+$/);
return match !== null ? Number(match[0]) : null;
}
numericSuffix('abc-123') // 123
numericSuffix('abc-123x') // null