0

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.

Barmar
  • 596,455
  • 48
  • 393
  • 495
  • 2
    `if (0|1|2|3|4|5|6|7|8|9)` will always be `true`. You're not actually checking whether it's any of those numbers but performing [bitwise arithmetic](https://stackoverflow.com/questions/6194950/what-does-the-single-pipe-do-in-javascript). – VLAZ Mar 24 '20 at 20:14
  • 1
    It can only be a string or a collection of numbers, what are you after exactly? Doesn't make sense to me as your question is now. – Phix Mar 24 '20 at 20:15
  • 1
    `if (x == '0' || x == '1' || ...)` – Barmar Mar 24 '20 at 20:17
  • This is not the main project code. In my project, i get value from input that is string but i want number. – Elias Achilles Mar 24 '20 at 20:18
  • 1
    `x.toString()` doesn't do anything, you need to do something with the result. Also, `x` is already a string, why do you think you need to convert it to a string. – Barmar Mar 24 '20 at 20:19
  • i do it for the plus and minus signs. – Elias Achilles Mar 24 '20 at 20:20
  • 2
    Your desired output is the same as the input. What's the point? – Barmar Mar 24 '20 at 20:23

2 Answers2

1

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; }
Mr. Polywhirl
  • 31,606
  • 11
  • 65
  • 114
0

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"));
OO7
  • 565
  • 2
  • 9