-2

I just learned about RegExp yesterday. I’m trying to figure something out: currently in a function I'm iterating through a string that's been split into an array to pull out and add up the numbers within it. There are examples like, 7boy20, 10, 2One, Number*1*, 7Yes9, Sir2, and 8pop2 which need to have the digits extracted.

So far, this only works to detect a single digit match:

var regexp = /(\d+)/g;

I've also tried:

var regexp =/(\d+)(\d?)/g; 

...but it was to no avail.

UPDATE: This is the code I've been using, and am trying to fix as some have asked:

var str = "7boy20 10 2One Number*1* 7Yes9 Sir2 8pop2";  
//var str = "7Yes9", "Sir2";  
//var str = "7boy20";  


function NumberAddition(str) {  
  input = str.split(" ");  
  var finalAddUp = 0;  
  var finalArr = [];  

  for(var i = 0; i<=input.length-1; i++) {  
    var currentItem = input[i];  
    var regexp = /(\d+)/g;  
    finalArr.push(currentItem.match(regexp));  
    var itemToBeCounted = +finalArr[i];  
    finalAddUp += itemToBeCounted;  
  }  
  console.log(finalArr);  
  return finalAddUp;  

//OUTPUT ---> [ [ '7', '20' ], [ '10' ], [ '2' ], [ '1' ], [ '7', '9' ], [ '2' ], [ '8', '2' ] ] (finalArr)

//OUTPUT --->NaN (finalAddUp)

How would I turn that output into numbers I can add up?

8
  • 1
    Can you give an example of the exact output you want? Commented May 29, 2014 at 0:58
  • ...and what is the method you use? Commented May 29, 2014 at 0:58
  • @DavidG Certainly. Here is the problem: I input a string like "7yes9 Sir2", and after being split into, "7yes9", and "Sir2", each is treated indidually. Next I run: for(var i = 0; i<=input.length-1; i++) { var currentItem = input[i]; var regexp = /(\d+)/g; finalArr.push(currentItem.match(regexp)); //var itemToBeCounted = (+finalArr[i]); //finalAddUp += itemToBeCounted; } Commented May 29, 2014 at 1:53
  • But my array for the above example "7yes9 Sir2" is, "[ [ '7', '9' ], [ '2' ] ]", so unfortunately for me, the numbers can't be added up. I know I can use Number with .match() when it's a single match like "10hello", but I can't with examples like "7yes9", again, and I'm stuck. @CasimiretHippolyte Commented May 29, 2014 at 1:55
  • @user3479657: regex are only a tool to extract substrings. If you want to add (or mulitply or divide...) numbers, you must first to extract them with a regex (or any ways you find) and only after you must add them but with other ways than regexes! (use the language). Commented May 29, 2014 at 2:58

4 Answers 4

2

Is this what you are looking for ?

This will give you every digit by them selves.

var re = /(\d)/g; 
var str = '123asdad235 asd 23:"#&22 efwsg34t\nawefqreg568794';
var m;

while ((m = re.exec(str)) != null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
}

This will give you the numbers and not just the digits.

var re = /(\d+)/g; 
var str = '123asdad235 asd 23:"#&22 efwsg34t\nawefqreg568794';
var m;

while ((m = re.exec(str)) != null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
}

Using the code from the last example m will be an array of all the numbers that you can SUM up using reduce Tho index 0 will always be the entire matched string, so skip that one...

m.reduce(function(previousValue, currentValue, index, array){
  return index === 0 ? 0 : previousValue + currentValue;
});
Sign up to request clarification or add additional context in comments.

Comments

1

To extract the numbers from the string, you can use one of these:

str.match(/\d+/g)
str.split(/\D+/)

And then, to sum the array, you can use

arr.reduce(function(a,b){ return +a + +b;});    // ES5
arr.reduce((a,b) => +a + +b);                   // ES6

Example:

"7boy20".split(/\D+/).reduce((a,b) => +a + +b); // Gives 27

Note that browser support for ES6 arrow functions is currently very small.

1 Comment

Very interesting, I wasn't aware about ES6 possibilities.
0

If you want a regex to match all digit:

var regDigit = /[^0-9.,]/g;

If you want a regex to match all letter:

var regString = /[^a-zA-Z.,]/g;

If you want to see the full JS code:

var s = ["7boy20", "10", "2One", "Number*1*", "7Yes9", "Sir2", , "8pop2"];

var regDigit = /[^0-9.,]/g;

var regString = /[^a-zA-Z.,]/g;

var extractDigit = s[0].replace(regDigit, '');

var extractString = s[0].replace(regString, '');

console.log("The extracted digit is " + extractDigit);

console.log("The extracted string is " + extractString);

Working Demo

4 Comments

This is almost perfect! However, the numbers are not separate. For "7yes9", in the above string, instead of "7, 9", or similar, I get----> "The extracted digit is 79"...AND... "The extracted string is Yes" On the other hand, when I use "7yes9 Sir2", then split, regex, and .push() them to an array, I would get [["7", "9"], ["2"]]. :(
I'm left unable to add up the results in the latter case, and in your case, the numbers are impossible to add up individually. But otherwise, this is very concise. Thanks for anything else you might add.
Sorry. I cant get what you mean.
I've updated my post above with the code I'm trying to fix. Maybe if you take a look you'll understand me? Please?
-2

To extract the digits, I would just replace the non-digits with nothing

var myregexp = /\D+/g;
result = subject.replace(myregexp, "");

7 Comments

Ron, I'm guessing that they down voted because since the OP wants to to pull out and add up the numbers, having all the numbers as one string will not make them able to be added together.
@Anonymous: If it is the case, the OP should better explain the requirements instead of downvote all the answers.
Thanks for the effort, but it doesn't seem to work, unfortunately. As was stated, I was looking for the ability to add up the numbers within it. Sorry if that wasn't specific enough somehow, casimiret.
@CasimiretHippolyte "OP" feels I was specific enough, and didn't downvote the question. Thanks for assuming anyway. Helpful.
@user3479657 Well, it seemed you were stuck on extracting all the digits, and that is what I addressed. You could certainly construct an addition formula by replacing the non-digits with plus signs, but that didn't seem to be your problem, and the best way to do it depends on more information than you had provided.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.