How  to extract numbers (integers) from a string using a function

How to extract numbers (integers) from a string using a function

In this blog post, I will show you how to create a function to extract numbers from a string. Just like in most of my posts, I ask myself "What do I need to accomplish this?" Let me refer to our blog title and break it down into small tasks.

1) How to extract numbers. We will need some way of extracting numbers, perhaps a filter rings a bell!

2) from a string. We will need a string of data to test our function.

3) using a function. which is a set of statements that performs a task or calculates a value. It will take an input which is the string and returns an output, the numbers from the string.

Our function will

  • take an input = string value
  • filter string values
  • convert string values to integers
  • output = return integers

At this point, we have enough information to start to code. We will start at number 2 to create a string of data.

myString = " 22.5, Callum, 45, Zaid, 1, .";

Now, we can move on to task 3 and create a function

function = extractNumbers() {
do something here!
}

In the next step, we need to pass data into the function, which we can achieve by adding a function argument "str".

function = extractNumbers(str) {
do something here!
}

Our next stage is to work on the "do something"!

First, Let me reverse a bit here and go back to number 1. We know that we need a filter method.

JavaScript has a filter() method for an Array, but we don't have an Array. In order to take advantage of the filter method, we need to convert the string to an Array.

We can use the split() method to separate the string into substrings and return an Array. The substrings will be the items separated by a "," comma in the original string. ie "22.5" is one substring and "Callum" is the next and so on. Using split() to split our string into substrings, we add what we call a "separator" The "separator" will be a double quote, then a comma and followed by a double quote. ie .split(",")

Note:

a) split() method without a separator will return the string as one element in an Array

const myString = " 22.5, Callum, 45, Zaid, 1, ."

let example1 = mystring.split();

console.log(example1);

//The result will be the original string as 1 element in an Array
//["22.5,Callum,45,Zaid,1,."]

b) split() method with " " will return each character as an individual substring

const myString = " 22.5, Callum, 45, Zaid, 1, .";

let example2 = mystring.split("");

console.log(example2);

//The result will be the original string with each character as an individual substring
//[["2","2",".","5",",","C","a","l","l","u","m",",","4","5",",","Z","a","i","d",",","1",",","."]

Ok, we now know that the split(",") method will return an array of substrings we need. We will require a name for the Array that the split(",") method returns.

Let us keep it simple and name it, "arrayOfStrings".

Continue with our code.

const myString = " 22.5, Callum, 45, Zaid, 1, .";

function = extractNumbers(str) {
  let arrayOfStrings = str.split(",");
  return arrayOfStrings;

}

console.log(extractNumbers(myString))

//result = ["22.5","Callum","45","Zaid","1","."]

You can see from the code above, that the array ArrayOfStrings has 3 numbers, 2 names and 1 period. The numbers in the array are not integers, but strings. Our function must return integer (numbers)

To prove my point, let me show you by using console.log. I will focus on the 1st element in the arrayOfStrings "arrayOfStrings[0]" and use typeof to return the data type.

const myString = " 22.5, Callum, 45, Zaid, 1, .";

function = extractNumbers(str) {
  let arrayOfStrings = str.split(",");
  return typeof arrayOfStrings[0];

}

console.log(extractNumbers(myString))

//using typeof with console.log
//result "string"

With this in mind, we will need to convert the number strings into integers. We can accomplish this by the Number() method. Learn more about the Number() method

In short, The Number() method converts a value to a number and If the value cannot be converted, NaN is returned.

We will need to run the Number() method on all the elements in the arrayOfStrings to convert number strings to integers.

The map() method is ideal for this as it returns an entirely new array with transformed elements and the same amount of data. Using the map method, we pass each element (element) into the Number() method.

function = extractNumbers(str) {
  let arrayOfStrings = str.split(",")
  return arrayOfStrings
                         .map((element)=>Number(element)); //convert all elements to numbers 

}

let's run our function and check out the result.

function = extractNumbers(str) {
  let arrayOfStrings = str.split(",");
  return arrayOfStrings
                         .map((element)=>Number(element)); //convert all elements to numbers 

}

console.log(extractNumbers(myString));


//result [22.5,NaN,45,NaN,1,NaN]

You can see from the code above our function has converted the string numbers to integers, but it also includes elements with the value of NaN (not a number). The NaN elements were the name strings i.e Zaid and Callum.

Remember our definition of the Number() method.

The Number() method converts a value to a number and If the value cannot be converted, NaN is returned. We will need to filter the array and return only the integers.

To filter out the NaN's we can use the function method isNaN. The isNaN() function determines whether a value is NaN or not. To filter the array for elements that are not a NaN value we will set the isNaN to false.

function extractNumbers(str) {
  let arrayOfStrings = str.split(",");
  return arrayOfStrings
                         .map((element)=>Number(element)) //convert all elements to numbers 
                         .filter((element)=>isNaN(element) === false); // only include if element is a number

}

console.log(extractNumbers(myString));


//result [22.5,45,1]

We have successfully created a function to return integers from a string. Congratulations!

But before we finish, can we do better with this code ?....

Let us refactor the code and place split(), map() and filter() on one line

const myString = " 22.5, Callum, 45, Zaid, 1, .";

function extractNumbers(str) {
let arrayOfStrings = str.split(",").map((e)=>Number(element)).filter((e)=>isNaN(e) === false);
return arrayOfStrings;

}

console.log(extractNumbers(myString)); //result [22.5,45,1]

Feel free to comment, share and review my other posts.

Thank you and happy coding!