Elias Achilles
Elias Achilles

Reputation: 89

How to convert only string digits to number?

var txt = '54839257+32648-34324';
var x;

for (x of txt) {
  if (0||1||2||3||4||5||6||7||8||9) {
    var con = Number(x);
  } else { x.toString();}
  
  document.write(con);
  
}

In the code above i want to convert the digits inside the string to number but not plus and minus signs. I want to have them together for the result. like this: 54839257+32648-34324. But my code gives this: 54839257NaN32648NaN34324.

Upvotes: 0

Views: 88

Answers (2)

OO7
OO7

Reputation: 690

For this case, simply you can use replace with regular expression.

const toNumber = (v) => {
     if (typeof v === "number") return v;
     if (typeof v !== "string") return;
     return  Number(v.replace(/[^0-9]/g, ""));
};

console.log(toNumber("OO7+54839257+32648-34324"));

Upvotes: 0

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48640

If you want to tokenize the numbers and symbols, but convert the integer values, you will need to split up the values first. The parenthesis around the symbols, inside the regular expression, allow you to capture the delimiter.

Afterwards, you can check if the value is numeric.

Edit: I changed the delimiter from [-+] to [^\d] as this makes more sense.

const input = '54839257+32648-34324';

const tokenize = (str) => {
  return str.split(/([^\d])/g).map(x => !isNaN(x) ? parseInt(x, 10) : x);
}

console.log(tokenize(input));
.as-console-wrapper { top: 0; max-height: 100% !important; }

Upvotes: 1

Related Questions