If I have a random string and want to encode it into another string that only contains alphanumeric characters, what is the most efficient way to do it in JavaScript / NodeJS?
Obviously it must be possible to convert the output string back to the original input string when needed.
Thanks!
If I have a random string and want to encode it into another string that only contains alphanumeric characters, what is the most efficient way to do it in JavaScript / NodeJS?
Obviously it must be possible to convert the output string back to the original input string when needed.
Thanks!
Share Improve this question asked Aug 16, 2015 at 16:42 PensierinmusicaPensierinmusica 6,97810 gold badges44 silver badges60 bronze badges 3-
What will be your input string look like? Also what do you mean by
only contains alphanumeric characters
? Does your input string contains non-alphanumeric characters? – Aruna Tebel Commented Aug 16, 2015 at 16:49 - Yes, the input string can contain any character, and the output string must contain only alphanumeric characters. – Pensierinmusica Commented Aug 16, 2015 at 16:51
- What is your purpose for the string conversion? – Trung Nguyen Commented Aug 16, 2015 at 16:53
2 Answers
Reset to default 11To encode to an alphanumeric string you should use an alphanumeric encoding. Some popular ones include hexadecimal (base16), base32, base36, base58 and base62. The alternatives to hexadecimal are used because the larger alphabet results in a shorter encoded string. Here's some info:
- Hexadecimal is popular because it is very mon.
- Base32 and Base36 are useful for case-insensitive encodings. Base32 is more human readable because it removes some easy-to-misread letters. Base32 is used in gaming and for license keys.
- Base58 and Base62 are useful for case-sensitive encodings. Base58 is also designed to be more human readable by removing some easy-to-misread letters. Base58 is used by Flickr, Bitcoin and others.
In NodeJS hexadecimal encoding is natively supported, and can be done as follows:
// Encode
var hex = new Buffer(string).toString('hex');
// Decode
var string = new Buffer(hex, 'hex').toString();
It's important to note that there are different implementations of some of these. For example, Flickr and Bitcoin use different implementations of Base58.
Why not just store the 2 strings in different variables so no need to convert back?
To extract all alphanumerics you could use the regex function like so:
var str='dssldjf348902.-/dsfkjl';
var patt=/[^\w\d]*/g;
var str2 = str.replace(patt,'');
str2
bees dssldjf348902dsfkjl