简体   繁体   中英

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]. 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM