FUNDAMENTAL

How to generate a number from the text in Javascript?

Generating a number from a text is an interesting problem.

In our day to day life as developers, we generally come to a problem where we want to calculate an equivalent number for a particular string.

Sometimes, we don't want absolute numbers but the equivalent number which might be distinguishable just.

If the text contains only numeric values in it, then it is very easy to convert it to a number in Javascript, and in fact, that equivalent number would be an absolute number.

IF TEXT CONTAINS NUMERIC VALUES:

If the text contains a numeric value only, then here is how we convert it to numbers.

Use + operator

By using plus (+) operator, we can convert it to numbers easily. You can find more information about the + operator in this article → How do Unary Plus and Unary Negation operators behave in Javascript?.

const text1 = '1234';
const num1 = +text1;
console.log(num1) // 1234

Use parseInt method

By using the parseInt method, we can also convert the text to numbers.

const text2 = '2345';
const num2 = parseInt(text2, 10); // here 10 is the base means we are converting it to decimal
console.log(num2);

IF TEXT CONTAINS NON NUMERIC VALUES:

If the text contains non-numeric values such as alphabets, special characters etc, then using the + operator or parseInt method will return NaN as the value.

It is next to impossible to find the absolute value of non-numeric text but we can find the equivalent random number for it.

So if you have a bunch of texts and you just need to give them some unique set of numbers or random numbers, we can do that.

Generate a random number

In order to calculate an equivalent number from the text, we need to

  1. Calculate the hex of the text (using CRC algorithms )
  2. Convert that hex value to decimal

In order to find the equivalent hex value of a text, we will be using crc npm package. We will use crc32 to convert text to the hex value.

import crc32 from "crc/crc32"
const hexVal = crc32("hello world").toString(16)
console.log(hexVal) // 'd4a1185'

Now using hexToDecimal converter, we can calculate the equivalent number.

const hexVal = "d4a1185"
function hexToDecimal(hexVal) {
return parseInt(hexVal, 16)
}
const num = hexToDecimal(hexVal)
console.log(num) // 222957957

So this is how we calculate the equivalent random number for a particular non-numeric text.