What is a method to pull out numerical values from a text in JavaScript without the use of regular expressions?

Consider this scenario: I have a string "asdf123d6lkj006m90" and I want to extract the values [123, 6, 0, 0, 6, 90]. My attempt so far is as follows:

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))

However, this code generates the result [1, 2, 3, 6, 0, 0, 6, 9, 0]. How can I modify it to get the correct numbers?

Answer №1

To efficiently parse the string for numbers, it's important to consider multiple characters at a time instead of focusing on just one.

def extract_numbers(s):
    nums = []
    current_num = ""
    
    for char in s:
        if char.isdigit():
            current_num += char
        elif current_num:
            nums.append(int(current_num))
            current_num = ""
        
    if current_num:
        nums.append(int(current_num))
    
    return nums

Despite the appearance of nested loops, this algorithm runs in linear time complexity (O(n)) since both loops iterate over the same array sequentially.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on accessing array values in MongoDB using Python syntax

Kindly, handle with care I have a mongo doc structured like this : { "Institute" : "Ucambridge", "Project" : [ #array of projects {"Sample":[ #array of samples { "workflow" : "abc", "owner" : "peter" } ...

What type of notation is being utilized here: someFunction([{property: data}, {property: data})

Recently, I stumbled upon a file with the .json extension as part of a larger project. Upon opening the JSON file, I noticed that it contained content similar to the following: someFunction([ {'key': 'value'}, {' ...

What method sits snugly between prepend() and append()?

Just a quick question I have. I am attempting to align an element with my target. Usually, we use prepend (before the target) and append (after the target). Is there something similar that allows us to position that element directly on top of what we are ...

Can someone clarify the distinction between returning a value directly or using Promise.resolve within the then() function?

What is the distinction between: new Promise(function(res, rej) { res("first example"); }) .then(function(result) { return "bbb"; // directly returning string }) .then(function(result) { console.log(result); }); and this: n ...

Are the charts missing from the Django admin interface?

I am working on incorporating charts into my admin view by extending the admin/base.html file. Instead of using libraries like charts.js, I prefer to use a template for displaying the charts. Ideally, I want my view to resemble this example (). You can fin ...

How to modify attributes using ng-content in Angular 2

Looking for a way to modify the attribute of the top div within the ng-content in my code. Here's an example snippet: <ng-container> <ng-content select="[content-body]"></ng-content> </ng-container> For instance, I want t ...

Calculate the difference and sum of time values with varying signs in JavaScript

-12:00 - 5:30 => -6:30 -2:00 - 5:30 => 3:30 00:00 - 5:30 => -5:30 6:00 - 2:30 => 3:30 I am interested in subtracting time with both positive and negative indices. let myCountries = [ { countryName: "NewZealand", ...

Angular generates an array that is not native to the system

When I directly set vm.files in my view using the following code: <input type="file" ng-model= vm.files[0]> <input type="file" ng-model= vm.files[1]> The contents of vm.files are displayed as shown in example A: https://i.stack.imgur.com/K3V ...

Optimal strategies for initializing Knockout JS models from backend code

Upon taking over a website that utilizes knockout js and asp.net, I noticed some performance issues during the initial page load. After investigating, I found that there are approximately 20 models on the site, each making an ajax call to retrieve data fro ...

Having issues with triggering a function from child props in React

I've been working on firing a function from an onClick event in a child component. getTotalOfItems = () => { console.log('anything at all?') if (this.props.cart === undefined || this.props.cart.length == 0) { return 0 } else { ...

Exploring jQuery Mobile - What Causes an Empty State?

Using $.mobile.navigate("#test-page", {id:123}) for navigation to a secondary page seems to be successful. The transition between pages is smooth.... but the state remains empty! According to the documentation, the state should contain all necessary info ...

Tips for concealing Bootstrap 5 modal exclusively after successful completion

Utilizing the power of Bootstrap 5 I have successfully implemented a modal that shows up when #truck_modal is clicked, thanks to the following JavaScript code: (this snippet is located at the beginning of my js file) document.addEventListener('DOMCo ...

Sending data from the server to the client in MVC using C#

I sent a token from a View to a function in my HomeController, and now I need to process the token and send back the information to the frontend. I assumed that the resultData returned by the ajax call would be the output of GetMyData, but it turns out it& ...

Interactive map with AngularJS featuring dynamic markers and real-time updating of marker position

In my Angular application, I have integrated a Google Map with a marker. I am looking to make the marker move along with the map as it is being moved. Currently, the marker stays in its default position when the map is moved. How can I achieve the effect ...

Tips for maintaining the integrity of blank space within a text node?

When intercepting a paste event and cleaning HTML off of the content using textNodes, I am faced with an issue where all white space is reduced to a single space and new lines are disregarded. For example, pasting: "hello world !" ends up being "h ...

How to make text dynamically shrink with TailwindCSS class 'flex-shrink-0'

I've designed an 'Album' (React) component to showcase album artwork, name, and release date in a card-like format. This component consists of two divs - one for the photo and the other for text. Each artist's discography displays multi ...

Are there any easy ways to sort arrays in PHP using usort?

When using PHP, the usort function requires two arguments: the array to be sorted and a callback function. The callback function also takes two arguments: $a and $b, which can be compared in any way desired. It is interesting to note that this particular u ...

What could be causing the issue with AJAX not running in a Python Django deployment on Heroku

My Django application is successfully deployed on Heroku, but I'm facing an issue with executing Ajax in the template. The Ajax functionality works perfectly fine on my local machine, however, it's not working on Heroku. I've included a snip ...

Can you transfer the elements of an array to a hash in Perl?

Here is an example of file content: >random sequence 1 consisting of 500 residues. VILVWRISEMNPTHEIYPEVSYEDRQPFRCFDEGINMQMGQKSCRNCLIFTRNAFAYGIV HFLEWGILLTHIIHCCHQIQGGCDCTRHPVRFYPQHRNDDVDKPCQTKSPMQVRYGDDSD; >random sequence 2 consisting of 500 resid ...

Optimal method for displaying content in Vue.js in read-only mode

I am currently working on a code snippet used to display messages exchanged between two users. <template> <main> <form action="" method="post" @submit.prevent="sendMessage"> <textarea name="message" id="messag ...