Home > Software design >  How to count number in a string using .match in JS)
How to count number in a string using .match in JS)

Time:10-08

could you please help me to solve this problem using .match regex? I dont know how to count numbers in this string. After I use match, I get an array and I cant plus those numbers together.

function func() {
  let count = 0;
  const text = "hi 3 how 10 are you 44"
  const regex = /\d /g; 
  const matches = text.match(regex); 

  if (count === 57) {
    return 'yes';
  }
}
func(); 

CodePudding user response:

Javascript Array method reduce is what you're looking for.

Here's a modified version of your function that will return the sum of numbers matches by your regex.

function func() {
  let count = 0;
  const text = "hi 3 how 10 are you 44"
  const regex = /\d /g;
  const matches = text.match(regex);

  if (!matches) return count; // no matches, return zero

  count = matches.reduce( // iterate over matches Array, passing through reduce function
    (acc, curr) => acc   parseInt(curr), // reduce values, sum matched numbers
    0 // initial value
  )

  return count
}

const someCondition = func();

if (someCondition === 57) {
  console.log('yes')
}

My next suggestion would be to pass text as a argument to the function func followed by renaming the function to something better, such as sumNumbersInString.

CodePudding user response:

Regex match returns an array, so just grab the length.

function func() {
    let string = 'hi 3 how 10 are you 44';
    let count = (string.match(/\d /g) || []).length;
    console.log(count);
    return count;
}
func()

  • Related