[英]How to get a number at the end of a string followed by this character `:` using regex
我需要在字符串的末尾得到一个数字(整数),然后加上以下字符:
。
基本上:
qwe-tyu-iop[-zxc:10 //result should be 10
::qwe-ty:u-iop[-zxc:10 //result should be 10
::qwe-ty:u-iop[-zxc:10.10 //result should be undefined
::qwe-ty:u-iop[-zxc:abc //result should be undefined
::qwe-ty:u-iop[-zxc:afdf10 //result should be undefined
只是
inputStr.split(":").pop();
例
function getValue( input ) { var value = input.split(":").pop(); return parseInt( value ) == value ? value : "undefined"; } console.log( getValue( "qwe-tyu-iop[-zxc:10" ) ); console.log( getValue( "::qwe-ty:u-iop[-zxc:10" ) ); console.log( getValue( "::qwe-ty:u-iop[-zxc:10.10" ) ); console.log( getValue( "::qwe-ty:u-iop[-zxc:abc" ) ); console.log( getValue( "::qwe-ty:u-iop[-zxc:afdf10" ) );
使用这种方法。 获取last的索引:
并从字符串中获取该部分。 如果不是数字,则parseInt
会给您NaN
const str = '::qwe-tyu-iop[-zxc:10'; const number = str.substring(str.lastIndexOf(':') + 1); console.log(Number.parseInt(number));
“QWE-TYU-IOP [-zxc:10” .match(/:\\ d + $ /?); // [“:10”]
这可以使用regex
以及使用纯JavaScript
来实现。
以下是两个选项:
使用正则表达式
const regex = /:(\d+)$/gm;
const str = `qwe-tyu-iop[-zxc:10`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
console.log(`Found match ---> ${m[1]}`);
}
仅使用JavaScript
const input = 'qwe-tyu-iop[-zxc:10';
const value = input.substring(input.lastIndexOf(':') + 1);
console.log(Number.parseInt(value) == value ? value : "undefined");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.