Motivational Quotes

Original quotes, wishes and messages for every day and every occasion

In this article
  1. Basic String Conversion
  2. Handling Hexadecimal and Bases
  3. Dealing with Whitespace and Edge Cases
  4. Type Checking Before Conversion
  5. Array and Object Mapping
  6. Regular Expression Extraction
  7. Practical Tips for Selection
  8. Frequently Asked Questions

JS Text to Number: Code Snippets & Conversion Tips

· 4 min read · Life & Wisdom

These JavaScript snippets are designed for developers who need to reliably transform string data into numeric values. Use them immediately in your projects to handle user input, parse API responses, or clean up messy datasets without writing boilerplate from scratch.

Basic String Conversion

Start with the simplest methods when you are sure the input is a clean number. These lines handle standard decimal integers and floats.

  • const num = Number("123"); console.log(num);
  • let val = +"45.67"; console.log(val);
  • const parsed = parseInt("89", 10); console.log(parsed);
  • let floatVal = parseFloat("12.34"); console.log(floatVal);
  • const result = "50" - 0; console.log(result);
  • let converted = Math.floor("67.8"); console.log(converted);
  • const strict = Number("99"); console.log(strict);
  • let quickCast = "100" * 1; console.log(quickCast);
  • const intVal = ~~"111"; console.log(intVal);
  • let simpleParse = parseInt("222"); console.log(simpleParse);

Handling Hexadecimal and Bases

When working with colors, memory addresses, or encoded data, you often need to interpret strings as different bases. These snippets ensure correct radix parsing.

  • const hex = parseInt("FF", 16); console.log(hex);
  • let octal = parseInt("77", 8); console.log(octal);
  • const binary = parseInt("1010", 2); console.log(binary);
  • let base32 = parseInt("ZZ", 36); console.log(base32);
  • const colorHex = parseInt("#AABBCC", 16); console.log(colorHex);
  • let mixedBase = parseInt("10", 2); console.log(mixedBase);
  • const validHex = parseInt("0x1A", 16); console.log(validHex);
  • let invalidBase = parseInt("12", 3); console.log(invalidBase);
  • const safeHex = parseInt("DEAD", 16); console.log(safeHex);
  • let zeroPad = parseInt("007", 10); console.log(zeroPad);

Dealing with Whitespace and Edge Cases

User input is rarely perfect. These examples show how to trim spaces and handle empty or malformed strings before conversion.

  • const trimmed = Number(" 123 "); console.log(trimmed);
  • let cleanStr = parseInt(" 456 ", 10); console.log(cleanStr);
  • const emptyResult = Number(""); console.log(emptyResult);
  • let nullHandle = Number(null); console.log(nullHandle);
  • const undefinedCheck = Number(undefined); console.log(undefinedCheck);
  • let boolToInt = Number(true); console.log(boolToInt);
  • const falseToZero = Number(false); console.log(falseToZero);
  • let nanCheck = Number("abc"); console.log(isNaN(nanCheck));
  • const infinityNum = Number("Infinity"); console.log(infinityNum);
  • let negativeStr = Number("-123"); console.log(negativeStr);

Type Checking Before Conversion

Prevent runtime errors by validating inputs. These patterns help you decide if a conversion is safe or if you should fallback to a default value.

  • function toNum(str) { return Number(str) || 0; }
  • let safeInt = parseInt("bad") || 0; console.log(safeInt);
  • const checkType = typeof Number("123"); console.log(checkType);
  • let isFinite = isFinite(Number("123")); console.log(isFinite);
  • const notANum = isNaN(Number("xyz")); console.log(notANum);
  • let fallback = Number("null") || 5; console.log(fallback);
  • const strictEq = Number("123") === 123; console.log(strictEq);
  • let coercedBool = !!Number("0"); console.log(coercedBool);
  • const truthyNum = Boolean(Number("1")); console.log(truthyNum);
  • let falsyNum = Boolean(Number("0")); console.log(falsyNum);

Array and Object Mapping

When processing lists of data, map over arrays to convert multiple values at once. These snippets demonstrate efficient bulk conversion.

  • let strArr = ["10", "20"].map(parseInt); console.log(strArr);
  • const cleaned = [" 5 ", " 6 "].map(s => Number(s.trim()));
  • let objKeys = Object.keys({a:"1"}).map(Number); console.log(objKeys);
  • const filterNums = ["1", "a", "2"].filter(v => !isNaN(Number(v)));
  • let reduceSum = ["1", "2"].reduce((a, b) => a + Number(b), 0);
  • const someValid = ["a", "1"].some(v => !isNaN(Number(v)));
  • let everyNum = ["1", "2"].every(v => !isNaN(Number(v)));
  • const findFirst = ["x", "5"].find(v => !isNaN(Number(v)));
  • let includesNum = ["1", "2"].includes(Number("1")); console.log(includesNum);

Regular Expression Extraction

Sometimes the number is hidden inside a larger string. Use regex to extract digits before converting them.

  • const match = "price: 100".match(/\d+/); const num = Number(match[0]);
  • let extract = "v2.0".replace(/[^0-9.]/g, ""); console.log(Number(extract));
  • const splitNum = "10,20".split(",").map(Number); console.log(splitNum);
  • let replaceAll = "1a2b3".replace(/[a-z]/gi, ""); console.log(Number(replaceAll));
  • const testMatch = "abc123def".match(/\d+/)[0]; console.log(Number(testMatch));
  • let globalMatch = "1 2 3".match(/\d+/g).map(Number); console.log(globalMatch);
  • const captureGroup = "id=456".match(/=(\d+)/)[1]; console.log(Number(captureGroup));
  • let lookahead = "123abc".match(/^\d+/); console.log(Number(lookahead[0]));
  • const backreference = "a1b2c3".match(/(\d)/g).map(Number); console.log(backreference);
  • let complexRegex = "cost $50.00".match(/\$([\d.]+)/)[1]; console.log(Number(complexRegex));

Practical Tips for Selection

Choose the right method based on your data source and desired output type. Always consider what happens when the input is unexpected.

  • Use Number() for strict conversion that returns NaN for invalid strings.
  • Use parseInt() when you need to ignore trailing non-numeric characters.
  • Always specify the radix in parseInt() to avoid octal interpretation bugs.
  • Trim whitespace before converting to prevent silent failures.
  • Test edge cases like empty strings, null, and undefined in your unit tests.

Frequently Asked Questions

What is the difference between Number() and parseInt()?

Number() converts the entire string to a floating-point number and returns NaN if any character is invalid. parseInt() parses only the leading numeric portion and ignores trailing non-numeric characters.

How do I handle empty strings during conversion?

An empty string passed to Number() returns 0, but parseInt() returns NaN. You can use logical OR operators to provide a fallback default value for both cases.

Why does parseInt("010") return 8 instead of 10?

Without a specified radix, older JavaScript engines may interpret strings starting with 0 as octal. Always pass 10 as the second argument to force decimal interpretation.

Can I convert an array of strings to numbers in one line?

Yes, use the Array.prototype.map() method with the Number function as the callback to transform all elements simultaneously.