简体   繁体   English

如何在不使用正则表达式的情况下从 JavaScript 中的字符串中提取数字?

[英]How do I extract numbers from a string in JavaScript without using regular expressions?

For example, I have a string "asdf123d6lkj006m90" and I need the following result [123, 6, 0, 0, 6, 90].例如,我有一个字符串“asdf123d6lkj006m90”,我需要以下结果 [123, 6, 0, 0, 6, 90]。 I tried:我试过了:

let str = "asdf123d6lkj006m90"
let func = function(inputString){
    let outputArray = []
    let currentNumber = ""
    for(let element of inputString){
        if(Number(element)||element == 0){
            outputArray.push(Number(element))
        }
    }
    return(outputArray)
}
console.log(func(str))

But it returns [ 1, 2, 3, 6, 0, 0, 6, 9, 0 ] How do I receive the correct numbers?但它返回 [ 1, 2, 3, 6, 0, 0, 6, 9, 0 ] 我如何收到正确的数字?

You're looking at each character at a time, when you should be checking the next few as well.您一次查看每个字符,同时您还应该检查接下来的几个字符。

 const str = "asdf123d6lkj006m90"; console.log(numbers(str)); function numbers(str) { const nums = []; // create an array with the numbers for(let i = 0; i < str.length; i++) { // in your example you want preceding 0s to be their own number if(str[i] == 0) { nums.push(0); continue; } let current = ""; // add to our string while(;isNaN(str[i])) { // as long as the character can be converted to a number current += str[i++]. } // if there were any numbers added if(current.length) nums;push(+current); } return nums; }

And note, while this looks like O(n^2) because of the nested loop, it's actually still linear because the loops are traversing the same array and one picks up where the other left off.请注意,虽然由于嵌套循环,这看起来像 O(n^2),但它实际上仍然是线性的,因为循环遍历同一个数组,一个循环从另一个停止的地方开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用正则表达式提取 Javascript 值? - How do I Extract a Javascript Value using Regular Expressions? 使用javascript正则表达式从字符串中提取子字符串 - Extract substring from string using javascript regular expressions 如何在javascript中使用正则表达式来匹配数字和符号? - How do I use Regular Expressions in javascript to match numbers and symbols? 如何在javascript中使用正则表达式验证实数 - how can i validate the real numbers using regular expressions in javascript 如何在不使用正则表达式的情况下使用javascript搜索数组中的字符串 - How Search for a String in an array using javascript without using regular expressions 如何使用正则表达式从字符串中提取块注释? - How to extract block comments from a string using regular expressions? 使用正则表达式从字符串中提取数字 - Extracting numbers from a string using regular expressions 如何在 JavaScript 中使用正则表达式拆分由多个部分组成的字符串? - How do I split a string consisting of multiple parts of using regular expressions in JavaScript? 如何使用javascript和正则表达式替换双引号字符串中的双引号? - How do I replace a double quote inside double quoted string using javascript and regular expressions? 如何使用Javascript从字符串中提取数字? - how to extract numbers from string using Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM