Extract all numerical values from a given string and store them in an array using JavaScript

Imagine having the following sequence:

'(01) Kyle Hall - Osc (04) Cygnus - Artereole (07) Forgemasters - Metalic (10) The Todd Terry Project - Back to the Beat (14) Broken Glass - Style of the Street'

You have the power to extract the numbers from this sequence and populate an array like so:

[01,04,07,10,14]

Answer №1

To extract numbers from a string, you can utilize a regular expression:

var numArray = str.match(/\d+/g);

Using this method will yield ["01", "04", "07", "10", "14"] (an array of strings). If you require the elements to be in number format, you can use .map(Number) for conversion:

var convertedNums = str.match(/\d+/g).map(Number);

This will give you [1, 4, 7, 10, 14].

Keep in mind that map may not be supported in IE versions prior to 9, so you might need to add a polyfill depending on your compatibility needs. You can find one readily available on MDN.

Answer №2

let string = '(01) Kyle Hall - Osc (04) Cygnus - Artereole (07) Forgemasters - Metalic (10) The Todd Terry Project - Back to the Beat (14) Broken Glass - Style of the Street';
let numbers = string.match(/\d+/g);
numbers.map(function (num) {
    return parseInt(num, 10);
});

For browsers that do not support Array.prototype.map, here is an alternative code:

let string = '(01) Kyle Hall - Osc (04) Cygnus - Artereole (07) Forgemasters - Metalic (10) The Todd Terry Project - Back to the Beat (14) Broken Glass - Style of the Street';
let numbers = string.match(/\d+/g);
for (let i = 0; i < string.length; i++) {
    string[i] = parseInt(string[i], 10);
}

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

What is the most efficient method for converting MySQL query results into an array using PHP?

As a PHP novice, I recently ran into an issue with storing values fetched from a select statement. The query returns 100 values for a specific record, and I want to store these in an array. Below is the snippet of code I've been working on: $result = ...

Using Javascript to assign a new key to an object by merging existing keys

I'm struggling to articulately explain my situation, so please excuse me if this has been addressed before. I am seeking to specify an object in the following manner: var foo = [ { firstName : 'John', lastName : 'Doe&ap ...

Encountering an endless loop when utilizing cycle-idb with a text field for user input

Struggling to develop a basic test app that captures user input from a text field, displays it, and stores it using cycle-idb. Unfortunately, I've been stuck in an endless loop no matter what steps I take. Below is the complete main function: functi ...

What is the best way to handle authentication tokens in a Node.js server application?

One challenge I'm facing is calling an API that requires a token to be passed, and this token needs to be refreshed. The main issue is - How and where should I store a token on the server? Some solutions on the internet suggest doing something like th ...

Is it possible to send a message from a child iframe to its parent using HTML5 cross-browser compatibility

I've been following this tutorial on a video-sharing website, which demonstrates how to securely pass messages between an iframe and its parent. The tutorial can be found at a specific URL. To achieve this functionality, you would end up with a simila ...

How is it possible for this C program to accurately display the number 7.21?

I understand that converting decimal fractions to binary can sometimes result in inaccuracies due to approximation. For example, 0.21 may not convert neatly into binary and therefore the representation in binary can be slightly off from the original decima ...

Tips for Preventing Websites from Hijacking Keyboard Shortcuts in Chrome Extension Development

Currently, I am developing a browser extension and have added an input form within a modal. However, I have encountered an issue where website shortcut key events take precedence over input key presses. As a result, I am unable to capture the input lette ...

How to remove elements from a JavaScript array: exploring the potential use of the delete function in JavaScript

I'm currently using Flot JS charts and I am attempting to completely remove a specific plot series from my data array either through jquery or plain javascript. Below is an example of what my data array consists of: [ { "label" : "Citrix PV Ether ...

Can the serialization of a user be avoided while connecting an account in PassportJS?

My application allows users to establish multiple oAuth connections to their account through PassportJS. Every time I connect another app using the Mailchimp strategy and Salesforce strategy, it logs me out of my session with Express. It seems like Passpo ...

How come uploading an image through the camera is functional on mobile Safari, but not on iOS as a Progressive Web App?

I am currently working on a webpage that has Progressive Web App (PWA) capabilities. When using iOS Safari, I encounter the regular OS dialog prompting me to choose between taking a photo or uploading one from the photo library: https://i.sstatic.net/eGE ...

The occurrence of "Error [ERR_STREAM_WRITE_AFTER_END]" was noted when trying to write to an HTTP server in

How to set up a new http server using Node.js After launching the server, the initial HTML text is displayed correctly. However, moving to other links in the code (e.g., localhost:5001/about) results in an error appearing in the IDE console. events.js:377 ...

Creating a dynamic div with various paragraphs using only Javascript

My goal is to dynamically generate paragraphs with their respective icons inside individual div elements. For instance, if the service API returns 30 items, I will create 30 div elements with the class "tile". However, if only one item is returned, then I ...

Smooth scrolling to an anchor with jQuery

Having recently written a simple smooth scrolling function using the jQuery mousewheel extension, I found myself facing a challenge due to my lack of experience with $.mousewheel. The gist of my issue is that when the "south delta" is triggered, I invoke ...

Error message: The Bootstrap .dropdown() method failed because it encountered an "Uncaught TypeError: undefined is not a function"

I've encountered an issue that seems to be a bit different from what others have experienced. Despite trying various solutions, I still can't seem to fix it. I suspect it might have something to do with how I'm importing my plugins. The erro ...

How to Execute a Java Method Using a JavaScript Function?

I've been doing some research, but haven't come across a straightforward answer to my question. Imagine I have an HTML page with embedded Javascript code, as well as a java.class file located in a package named somePackage.someSubPackage.*; Is t ...

Looking to switch up the hide/show toggle animation?

Currently, I have a functioning element with the following code. It involves an object named #obj1 that remains hidden upon page load but becomes visible when #obj2 is clicked. #obj1{ position:fixed; width:100px; bottom:180px; right:10 ...

Iterate through the array to verify that the specified conditions are satisfied for each individual item

I am working with an array of items and need to check if they all meet specific criteria. I've created a for loop to iterate through the array, but I'm concerned about its efficiency. Is there a more optimal way to achieve this? let match = 0; ...

Determine the matching rate between two arrays of integer values

I am trying to calculate the match rate between two arrays based on their values. For example, if one array is [9] and the other is [9], the match rate would be 100%. If one array is [9] and the other is [4], the rate would be 50%. And if one array is [4, ...

What is the most efficient way to retrieve the full file path from a client using jQuery or JavaScript?

Similar Issue: Dealing with fake path errors during file uploads ASP.NET: Solutions for retrieving client-side file paths I am trying to retrieve the full path of a client's file and send it to a webservice. However, I am unable to access the ...

Retrieve three distinct elements from an array in Swift, each containing unique values

In my current project, I am working with an array of key/value pairs and have a unique requirement to retrieve a random number of items. The catch is that the values must be distinct and no item can be returned multiple times. Here is an example of the da ...