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.

7
  • 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. Commented Mar 24, 2020 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. Commented Mar 24, 2020 at 20:15
  • 1
    if (x == '0' || x == '1' || ...) Commented Mar 24, 2020 at 20:17
  • 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. Commented Mar 24, 2020 at 20:19
  • 2
    Your desired output is the same as the input. What's the point? Commented Mar 24, 2020 at 20:23

2 Answers 2

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; }

Sign up to request clarification or add additional context in comments.

Comments

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"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.