Define only input tokens in input (JavaScript)

I am trying to calculate the sum of only numeric tokens, not numbers that are bound to words.

Example

"11 M22 33"

- the sum will be 44 because 22 is tied to M

I wrote this function, but it seems like it adds all numbers. How to highlight regex tokens only?

<FORM> 
<input type="text" name="phrase" id="calc" value="Enter code" /> 

<input type="button" value="calcule" onclick="lasomme();" /> 

<input type="button" value="invers" onclick="inverser();" /> 
</FORM> 


<script>

function lasomme() 
{ 

/*var calcule = document.getElementById("calc").value; 
alert(calcule);*/

var k = /^[A-Za-z\-éèàùâêûîôäëüïö]+$/;
var r = /\d+/g;
var s = document.getElementById("calc").value;
var m;
var sam =0;

while ((m = k.r.exec(s)) != null) {
   sam += parseInt(m);
  m++;
  
}
alert (sam);

} 




</script>
      

Run codeHide result


Is there a way to only calculate numbers and not numbers?

thank

+3


source to share


2 answers


Here you go



str = "11 M22 33";

sum = str.match(/\b\d+\b/g).reduce((a, b) => Number(a) + Number(b));

console.log(sum);
      

Run codeHide result


\b

is a word-boundary metacharacter, it ensures that the expression only matches numbers that are separate words.

+2


source


Try this formula:



(?:\s|^)\d+(?:\s|$)

+2


source







All Articles