anthonycrisart anthonycrisart - 5 months ago 6
Javascript Question

Convert strings with many numbers then add all

So far this code for me is working:

var x;
var y;
var z;

function functionWithArgs(x, y, z) {
console.log(x + y + parseInt(z)); // I get a sum of 6
}

functionWithArgs(1, 2, "3b");


But when I do this:

var x;
var y;
var z;

function functionWithArgs(x, y, z) {
console.log(x + y + parseInt(z)); //
}

functionWithArgs(1, 2, "987b8h76");


I get an error message. Any suggestions please. I'm just a beginner.

Answer

Try this:

function functionWithArgs(x, y, z) {
  console.log(x + y + parseInt(z.replace(/\D+/g, ''), 10));
}

functionWithArgs(1, 2, "987b8h76");  // 987879