How to add spaces to every two numbers with JavaScript? - javascript

I like to output a formatted number with a space after every two numbers, I've tried this:
function twoSpaceNumber(num) {
return num.toString().replace(/\B(?<!\.\d)(?=([0-9]{2})+(?!\d))/g, " ");
}
twoSpaceNumber(12345678) => 1 23 45 67 89 ( should start with 12 ? )
and also when it starts with 0 I had very strange output
twoSpaceNumber(012345678) => 12 34 56 78

Please consider
var s = "1234456";
var t = s.match(/.{1,2}/g);
var u = t.join(" ");
console.log(u);
which logs
12 34 45 6
and
var s = "ABCDEF";
var t = s.match(/.{1,2}/g);
var u = t.join(" ");
console.log(u);
which logs
AB CD EF
Note that s is a string.
Is that what you need?

Pass num as a string, not a number, else the leading zeros will disappear and use
function twoSpaceNumber(num) {
return num.replace(/\d{2}(?!$)/g, "$& ");
}
The regex matches two digits that are not at the end of string (in order not to add a space at the string end).
JavaScript demo
const regex = /\d{2}(?!$)/g;
function twoSpaceNumber(num) {
return num.replace(regex, "$& ");
}
const strings = ['123456789','012345678'];
for (const string of strings) {
console.log(string, '=>', twoSpaceNumber(string));
}

If you don't mind a non-regex approach:
function twoSpaceNumber(num) {
var res = '';
num += '';
for(var i = 0; i < num.length; i+=2)
{
res += num.substr(i,2) + ' ';
}
return res.trim();
}

Related

How to split string between 2 patterns in javascript

i want to split string between 2 patterns so that i will get correct item
i want to split below string between
_333/4444.json or _(3 or 4 numbers).json
Below is my pattern:
"test_halloween Party 10 AM - 12:30 PM party_560.json"
"Kaulampur 1110 reva_2018 RR_999 Roadrover_4987.json"
split based on :
_560.json
_4987.json
Final Output:
1) 560
2) 4987
here is what i have tried:
var str1 = "test_halloween Party 10 AM - 12:30 PM party_560.json";
var str2 = "Kaulampur 1110 reva_2018 RR_999 Roadrover_4987.json";
var res1 = str1.split(/_./)[0];
var res2 = str2.split(/_./)[0];
console.log(res1);
console.log(res2);
Note: a single pattern should give me both results
Try a regular expression.
Here's a good primer on how they work: https://www.codepicky.com/regex/
/_(\d{3,4})\.json$/
What is happening with this pattern?
The beginning and ending / are simply bookends defining a pattern
The _ literal will match the underscore that precedes the digits
(\d{3,4}) defines a "capture group" that matches exactly 3 or 4 consecutive numeric digits. This is handy because it lets us extract the digits you want separately from the overall pattern.
\.json$ matches the string .json (you have to escape the period with a slash because it is a special regex character) and the $ enforces it being at the end of the string
Example:
let result1 = "test_halloween Party 10 AM - 12:30 PM party_560.json".match(/_(\d{3,4})\.json$/);
// result1[1] === 560
let result2 = "Kaulampur 1110 reva_2018 RR_999 Roadrover_4987.json".match(/_(\d{3,4})\.json$/);
// result2[1] === 4987
let result3 = "this string will not match".match(/_(\d{3,4})\.json$/);
// result === null
Regular expressions are extremely versatile, precise, and fast. Take a look at this benchmark comparing it to a string index-finding alternative: http://jsben.ch/lbfUt
I'd solve it like this (slower than pre-compiled regex):
function myFunc(s) {
let i = s.lastIndexOf("_");
let j = s.indexOf(".", i);
return s.substring(i+1, j);
}
console.log(
myFunc("test_halloween Party 10 AM - 12:30 PM party_560.json"),
myFunc("Kaulampur 1110 reva_2018 RR_999 Roadrover_4987.json")
);
Anyone interested in the hand-coded DFA mentioned in comments:
function myFunc(s) {
const MAX = 10;
t = s.substr(-MAX);
for (let i=0; i<MAX; i++) {
let z = "";
if (t[i] === "_") {
i++;
if (isd( t[i] )) {
z += t[i];
i++;
if (isd( t[i] )) {
z += t[i];
i++;
if (isd( t[i] )) {
z += t[i];
i++;
const IS_DOT = 1;
const IS_DIGIT = 2;
let x = (t[i] === ".")
? IS_DOT
: (isd(t[i]))
? IS_DIGIT
: 0;
OUT:
while (true) {
switch (x) {
case IS_DOT:
i++;
if (t.substring(i) === "json") {
return z;
}
break;
case IS_DIGIT:
z += t[i];
i++;
x = IS_DOT;
break;
default:
break OUT;
}
}
}
}
}
}
}
return null;
}
function isd(c) {
let x = c.charAt(0);
return (x >= "0" && x <= "9");
}
console.log(
[
"_asnothusntaoeu_2405.json",
"_asnothusntaoeu_105.json",
"_asnothusntaoeu_5.json",
"_asnothusntaoeu.json",
"_asnothusntaoeu_5json",
"_asnothusntaoeu_5.jso",
"_asnothusntaoeu_105.json"
].map(s => myFunc(s))
);
try this var res1 = /([0-9]+)\.json$/.exec(str1)[1];
This seems like a textbook case of when you'd just want to use a Regular Expression. Something like:
// Select all things of the form "_<numbers>.json" from
// the string, and parse out <numbers> as a match.
var MyRegEx = /_(\d+)\.json/i;
var str1 = "test_halloween Party 10 AM - 12:30 PM party_560.json";
var res1 = MyRegEx.exec(str1)[1];
var str2 = "Kaulampur 1110 reva_2018 RR_999 Roadrover_4987.json";
var res2 = MyRegEx.exec(str2)[1];
console.log(res1);
console.log(res2);
That should do the trick.

How to generate a Random token of 32 bit in Javascript?

I need to generate an accurate 32 bits random alphanumeric string in JavaScript.Is there any direct function to do it ?
Using crypto and a typed array;
function random32bit() {
let u = new Uint32Array(1);
window.crypto.getRandomValues(u);
let str = u[0].toString(16).toUpperCase();
return '00000000'.slice(str.length) + str;
}
This gives us a 32-bit crypto-random number represented as a zero-padded string of 8 chars (base 16)
If you want to extend this to arbitrary numbers of chars;
function randomHash(nChar) {
let nBytes = Math.ceil(nChar = (+nChar || 8) / 2);
let u = new Uint8Array(nBytes);
window.crypto.getRandomValues(u);
let zpad = str => '00'.slice(str.length) + str;
let a = Array.prototype.map.call(u, x => zpad(x.toString(16)));
let str = a.join('').toUpperCase();
if (nChar % 2) str = str.slice(1);
return str;
}
In ES5, with comments
function randomHash(nChar) {
// convert number of characters to number of bytes
var nBytes = Math.ceil(nChar = (+nChar || 8) / 2);
// create a typed array of that many bytes
var u = new Uint8Array(nBytes);
// populate it wit crypto-random values
window.crypto.getRandomValues(u);
// convert it to an Array of Strings (e.g. "01", "AF", ..)
var zpad = function (str) {
return '00'.slice(str.length) + str
};
var a = Array.prototype.map.call(u, function (x) {
return zpad(x.toString(16))
});
// Array of String to String
var str = a.join('').toUpperCase();
// and snip off the excess digit if we want an odd number
if (nChar % 2) str = str.slice(1);
// return what we made
return str;
}
I need to generate an accurate 32 bits random alphanumeric string in
JavaScript.
If you mean 32 characters, you can use URL.createObjectURL, String.prototype.slice(), String.prototype.replace()
var rand = URL.createObjectURL(new Blob([])).slice(-36).replace(/-/g, "")
Inspired by Paul S.'s answer but a little simpler:
const Token = () => {
const array = new Uint32Array(1)
window.crypto.getRandomValues(array)
return array[0].toString(36)
}
You can use this function:
function returnHash(){
abc = "abcdefghijklmnopqrstuvwxyz1234567890".split("");
var token="";
for(i=0;i<32;i++){
token += abc[Math.floor(Math.random()*abc.length)];
}
return token; //Will return a 32 bit "hash"
}
Use by calling returnHash()
This will generate the 32 bit random alphanumeric string as requested:
crypto.getRandomValues(new Uint8Array(4)).reduce((p,c)=>p+String.fromCharCode(c))

Javascript - how to get 3 digit from a random string where the length is sometimes not static?

I have this random values where 90% time t0, t1 has same length. But 10% time its exceptional.
var t0 ="6M1000000000000/1111111 XNFVSD XXXXXXXX 0298 0101010A0001 148";
var t1 ="6M1ABDDERREDDDDDD/EOPPP XPSWKQ X2222222 8081 1010101A0132 100 1221212 dfdf111";
var t2 ="6M1XEEDDD/XXXEEE XTRY3U X1XXXXXX 0921 104Y011A114 148 01010101993938 11212>1122";
Now in all cases i have to get 3 values 114 from (104Y011A114), 132 from (1010101A0132) and 001 from (0101010A0001).
I have used
var find_3_digit = 0;
var input = t2; // or t1, t0
for(var i = 0; i< input.length; i++ ){
if( (i>=53) && (i<=56) ) {
console.log('H - ', input[i]);
find_3_digit += input[i];
}
}
but because t2 is exceptional i get value 14 not 114 (which is breaking my logic).
So, how can i have a way to get: 001 from t0, 132 from t1, 114 from t2?
You can split on more than 1 space. Return the section that has your numbers in it, which I'm assuming will always be index 4, and then return the last 3 characters.
function getThreeDigits(string) {
return String(string).split(/ +/)[4].substr(this.length - 3);
}
var t0 ="6M1000000000000/1111111 XNFVSD XXXXXXXX 0298 0101010A0001 148";
var t1 ="6M1ABDDERREDDDDDD/EOPPP XPSWKQ X2222222 8081 1010101A0132 100 1221212 dfdf111";
var t2 ="6M1XEEDDD/XXXEEE XTRY3U X1XXXXXX 0921 104Y011A114 148 01010101993938 11212>1122";
getThreeDigits(t0); // 001
getThreeDigits(t1); // 132
getThreeDigits(t2); // 114
Use regular expression! Use groups for get needed group of symbols and get last three characters.
First remove duplicated white spaces from string, than split on white space, and finally take 5th element's last 3 characters:
$(document).ready(function() {
var strings = [
"6M1000000000000/1111111 XNFVSD XXXXXXXX 0298 0101010A0001 148",
"6M1ABDDERREDDDDDD/EOPPP XPSWKQ X2222222 8081 1010101A0132 100 1221212 dfdf111",
"6M1XEEDDD/XXXEEE XTRY3U X1XXXXXX 0921 104Y011A114 148 01010101993938 11212>1122"
];
var log = $('#log');
$.each(strings, function() {
var string = this;
//remove duplicate spaces
string = string.replace(/\s+/g, ' ');
//split on spaces
var subStrings = string.split(' ');
//take last 3 chars
var value = subStrings[4].slice(-3);
log.append(this + ' - ' + subStrings[4].slice(-3) + '<br/>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="log">
</div>
It can be done with this function:
function GetDigits(input) {
var find_3_digit = "";
for (var i = 56; find_3_digit.length < 3; i--) {
if (input[i] != " ")
find_3_digit = input[i] + find_3_digit;
}
return find_3_digit;
}
See this JSFiddle

Hexadecimal Globally Unique Identifier (GUID) Algorithm in Node/JavaScript

Is it possible to create a GUID using 16 characters of hex? The reason I ask is Cloudflare is using 16 characters to identify each request to their system (they call them "Ray IDs"). They look much nicer compared to other GUID formats (I know this is silly preference).
The key space would contain these characters:
0-9
a-f
---
16 total possible characters
Example: adttlo9dOd8haoww
Also, any hint to a basic algorithm of generating these things would be awesome.
Lastly, I'm open to leaving the "hex" format and using:
0-9
a-z
A-Z
---
62 total possible characters
Example: dhmpLTuPFWEwM8UL
When you need to create your own unique id's use date time now. If your application is distributed use datetime.now + node identifier this is the most simple solution:
function d2h(d) {
return d.toString(16);
}
function h2d (h) {
return parseInt(h, 16);
}
function stringToHex (tmp) {
var str = '',
i = 0,
tmp_len = tmp.length,
c;
for (; i < tmp_len; i += 1) {
c = tmp.charCodeAt(i);
str += d2h(c) + ' ';
}
return str;
}
function hexToString (tmp) {
var arr = tmp.split(' '),
str = '',
i = 0,
arr_len = arr.length,
c;
for (; i < arr_len; i += 1) {
c = String.fromCharCode( h2d( arr[i] ) );
str += c;
}
return str;
}
//if you can get utc time is even bether
// Tue, 30 Jun 2015 23:01:04 GMT
var time = Date();
var server_point = "S1";
//you can encript this genrated id with blow fish or something, remember encripting existen bytes the length of the result wil grow
//remove spaces
var reg = new RegExp("[ ]+","g");
time = time.replace(reg, "");
var hexaResult = stringToHex(time + server_point);
alert(hexaResult.replace(reg, ""));
Or you can use crypto random generator:
https://developer.mozilla.org/en-US/docs/Web/API/RandomSource/getRandomValues
Guids are typically 32 hex characters with dashes at different intervals.
var crypto = require("crypto");
function create_guid() {
var hexstring = crypto.randomBytes(16).toString("hex"); // 16 bytes generates a 32 character hex string
var guidstring = hexstring.substring(0,8) + "-" + hexstring.substring(8,12) + "-" + hexstring.substring(12,16) + "-" + hexstring.substring(16,20) + "-" + hexstring.substring(20);
return guidstring;
}
You can simply modify the above function to return hexstring instead of guidstring if you don't want the dashes. And if want just 16 characters instead of 32:
function create_guid_simple() {
var hexstring = crypto.randomBytes(8).toString("hex"); // 8 bytes is a 16 character string
return hexstring;
}

How to convert text to binary code in JavaScript?

I want JavaScript to translate text in a textarea into binary code.
For example, if a user types in "TEST" into the textarea, the value "01010100 01000101 01010011 01010100" should be returned.
I would like to avoid using a switch statement to assign each character a binary code value (e.g. case "T": return "01010100) or any other similar technique.
Here's a JSFiddle to show what I mean. Is this possible in native JavaScript?
What you should do is convert every char using charCodeAt function to get the Ascii Code in decimal. Then you can convert it to Binary value using toString(2):
function convert() {
var output = document.getElementById("ti2");
var input = document.getElementById("ti1").value;
output.value = "";
for (var i = 0; i < input.length; i++) {
output.value += input[i].charCodeAt(0).toString(2) + " ";
}
}
<input id="ti1" value ="TEST"/>
<input id="ti2"/>
<button onClick="convert();">Convert!</button>
And here's a fiddle: http://jsfiddle.net/fA24Y/1/
This might be the simplest you can get:
function text2Binary(string) {
return string.split('').map(function (char) {
return char.charCodeAt(0).toString(2);
}).join(' ');
}
traverse the string
convert every character to their char code
convert the char code to binary
push it into an array and add the left 0s
return a string separated by space
Code:
function textToBin(text) {
var length = text.length,
output = [];
for (var i = 0;i < length; i++) {
var bin = text[i].charCodeAt().toString(2);
output.push(Array(8-bin.length+1).join("0") + bin);
}
return output.join(" ");
}
textToBin("!a") => "00100001 01100001"
Another way
function textToBin(text) {
return (
Array
.from(text)
.reduce((acc, char) => acc.concat(char.charCodeAt().toString(2)), [])
.map(bin => '0'.repeat(8 - bin.length) + bin )
.join(' ')
);
}
Here's a pretty generic, native implementation, that I wrote some time ago,
// ABC - a generic, native JS (A)scii(B)inary(C)onverter.
// (c) 2013 Stephan Schmitz <eyecatchup#gmail.com>
// License: MIT, http://eyecatchup.mit-license.org
// URL: https://gist.github.com/eyecatchup/6742657
var ABC = {
toAscii: function(bin) {
return bin.replace(/\s*[01]{8}\s*/g, function(bin) {
return String.fromCharCode(parseInt(bin, 2))
})
},
toBinary: function(str, spaceSeparatedOctets) {
return str.replace(/[\s\S]/g, function(str) {
str = ABC.zeroPad(str.charCodeAt().toString(2));
return !1 == spaceSeparatedOctets ? str : str + " "
})
},
zeroPad: function(num) {
return "00000000".slice(String(num).length) + num
}
};
and to be used as follows:
var binary1 = "01100110011001010110010101101100011010010110111001100111001000000110110001110101011000110110101101111001",
binary2 = "01100110 01100101 01100101 01101100 01101001 01101110 01100111 00100000 01101100 01110101 01100011 01101011 01111001",
binary1Ascii = ABC.toAscii(binary1),
binary2Ascii = ABC.toAscii(binary2);
console.log("Binary 1: " + binary1);
console.log("Binary 1 to ASCII: " + binary1Ascii);
console.log("Binary 2: " + binary2);
console.log("Binary 2 to ASCII: " + binary2Ascii);
console.log("Ascii to Binary: " + ABC.toBinary(binary1Ascii)); // default: space-separated octets
console.log("Ascii to Binary /wo spaces: " + ABC.toBinary(binary1Ascii, 0)); // 2nd parameter false to not space-separate octets
Source is on Github (gist): https://gist.github.com/eyecatchup/6742657
Hope it helps. Feel free to use for whatever you want (well, at least for whatever MIT permits).
var PADDING = "00000000"
var string = "TEST"
var resultArray = []
for (var i = 0; i < string.length; i++) {
var compact = string.charCodeAt(i).toString(2)
var padded = compact.substring(0, PADDING.length - compact.length) + compact
resultArray.push(padded)
}
console.log(resultArray.join(" "))
The other answers will work for most cases. But it's worth noting that charCodeAt() and related don't work with UTF-8 strings (that is, they throw errors if there are any characters outside the standard ASCII range). Here's a workaround.
// UTF-8 to binary
var utf8ToBin = function( s ){
s = unescape( encodeURIComponent( s ) );
var chr, i = 0, l = s.length, out = '';
for( ; i < l; i ++ ){
chr = s.charCodeAt( i ).toString( 2 );
while( chr.length % 8 != 0 ){ chr = '0' + chr; }
out += chr;
}
return out;
};
// Binary to UTF-8
var binToUtf8 = function( s ){
var i = 0, l = s.length, chr, out = '';
for( ; i < l; i += 8 ){
chr = parseInt( s.substr( i, 8 ), 2 ).toString( 16 );
out += '%' + ( ( chr.length % 2 == 0 ) ? chr : '0' + chr );
}
return decodeURIComponent( out );
};
The escape/unescape() functions are deprecated. If you need polyfills for them, you can check out the more comprehensive UTF-8 encoding example found here: http://jsfiddle.net/47zwb41o
Just a hint into the right direction
var foo = "TEST",
res = [ ];
foo.split('').forEach(function( letter ) {
var bin = letter.charCodeAt( 0 ).toString( 2 ),
padding = 8 - bin.length;
res.push( new Array( padding+1 ).join( '0' ) + bin );
});
console.log( res );
8-bit characters with leading 0
'sometext'
.split('')
.map((char) => '00'.concat(char.charCodeAt(0).toString(2)).slice(-8))
.join(' ');
If you need 6 or 7 bit, just change .slice(-8)
Thank you Majid Laissi for your answer
I made 2 functions out from your code:
the goal was to implement convertation of string to VARBINARY, BINARY and back
const stringToBinary = function(string, maxBytes) {
//for BINARY maxBytes = 255
//for VARBINARY maxBytes = 65535
let binaryOutput = '';
if (string.length > maxBytes) {
string = string.substring(0, maxBytes);
}
for (var i = 0; i < string.length; i++) {
binaryOutput += string[i].charCodeAt(0).toString(2) + ' ';
}
return binaryOutput;
};
and backward convertation:
const binaryToString = function(binary) {
const arrayOfBytes = binary.split(' ');
let stringOutput = '';
for (let i = 0; i < arrayOfBytes.length; i++) {
stringOutput += String.fromCharCode(parseInt(arrayOfBytes[i], 2));
}
return stringOutput;
};
and here is a working example: https://jsbin.com/futalidenu/edit?js,console
Provided you're working in node or a browser with BigInt support, this version cuts costs by saving the expensive string construction for the very end:
const zero = 0n
const shift = 8n
function asciiToBinary (str) {
const len = str.length
let n = zero
for (let i = 0; i < len; i++) {
n = (n << shift) + BigInt(str.charCodeAt(i))
}
return n.toString(2).padStart(len * 8, 0)
}
It's about twice as fast as the other solutions mentioned here including this simple es6+ implementation:
const toBinary = s => [...s]
.map(x => x
.codePointAt()
.toString(2)
.padStart(8,0)
)
.join('')
If you need to handle unicode characters, here's this guy:
const zero = 0n
const shift = 8n
const bigShift = 16n
const byte = 255n
function unicodeToBinary (str) {
const len = str.length
let n = zero
for (let i = 0; i < len; i++) {
const bits = BigInt(str.codePointAt(i))
n = (n << (bits > byte ? bigShift : shift)) + bits
}
const bin = n.toString(2)
return bin.padStart(8 * Math.ceil(bin.length / 8), 0)
}
this seems to be the simplified version
Array.from('abc').map((each)=>each.charCodeAt(0).toString(2)).join(" ")
This is as short as you can get. It's based on the top-rated answer but transformed to a reduce function.
"TEST".split("").reduce(function (a, b) { return a + b.charCodeAt(0).toString(2)}, "")
const textToBinary = (string) => {
return string.split('').map((char) =>
char.charCodeAt().toString(2)).join(' ');
}
console.log(textToBinary('hello world'))
var UTF8ToBin=function(f){for(var a,c=0,d=(f=unescape(encodeURIComponent(f))).length,b="";c<d;c++){for(a=f.charCodeAt(c).toString(2);a.length%8!=0;){a="0"+a}b+=a}return b},binToUTF8=function(f){for(var a,c=0,d=f.length,b="";c<d;c+=8){b+="%"+((a=parseInt(f.substr(c,8),2).toString(16)).length%2==0?a:"0"+a)}return decodeURIComponent(b)};
This is a small minified JavaScript Code to convert UTF8 to Binary and Vice versa.
This is a solution for UTF-8-based textual binary representation. It leverages TextEncoder, which encodes a string to its UTF-8 bytes.
This solution separates characters by spaces. The individual "byte-bits" of multi-byte characters are separated by a minus character (-).
// inspired by https://stackoverflow.com/a/40031979/923560
function stringToUtf8BinaryRepresentation(inputString) {
const result = Array.from(inputString).map(
char => [... new TextEncoder().encode(char)].map(
x => x.toString(2).padStart(8, '0')
).join('-')
).join(' ');
return result;
}
// ### example usage #########################
function print(inputString) {
console.log("--------------");
console.log(inputString);
console.log(stringToUtf8BinaryRepresentation(inputString));
}
// compare with https://en.wikipedia.org/wiki/UTF-8#Encoding
// compare with https://en.wikipedia.org/wiki/UTF-8#Codepage_layout
// compare with UTF-16, which JavaScript uses for strings: https://en.wikipedia.org/wiki/UTF-16#Examples
print("TEST");
print("hello world");
print("$");
print("Β£");
print("€");
print("ν•œ");
print("𐍈");
print("παράδΡιγμα");
print("🀑");
print("πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦");
print("πŸ‘©πŸ»β€πŸ€β€πŸ§‘πŸΏ");
print("πŸ‡ΊπŸ‡¦");
use the code: 'text'.split('').map(e=>{return e.charCodeAt(0).toString(2)}) e.g.-
const text='some text';
const output=text.split('').map(e=>{return e.charCodeAt(0).toString(2)})
Simple using Buffer
const text = "TEST";
[...Buffer.from(text).values()] // [ 84, 69, 83, 84 ]
.map(byte => byte.toString(2).padStart(8, 0)) // [ '01010100', '01000101', '01010011', '01010100' ]
.join(' ') // '01010100 01000101 01010011 01010100'
The shortest and simplest solution:
"x".charCodeAt().toString(2) // 1111000
String.charCodeAt() charCodeAt(0) returns unicode: "x".charCodeAt() // 120
Object.toString() charCodeAt().toString(2) converts unicode to binary.
For multiple string characters:
[..."Tesla"].map((i) => i.charCodeAt().toString(2)).join(" ");
// 1010100 1100101 1110011 1101100 1100001
Spread syntax (...)
[..."Tesla"] // ['T', 'e', 's', 'l', 'a']
Array.map()
[..."Tesla"].map((i) => i.charCodeAt()) // [84, 101, 115, 108, 97]
Array.join() Put a space " " after each element in the array map(i) and convert the array to string.
I'm pretty sure that you can do something like this:
Returns a STRING:
const toBinary = (str)=>{
let r = []
for (let i=0; i<str.length; i++) {
r.push(str.charCodeAt(i).toString(2));
}
return r.join("");
}
Or, as an int:
const toBinary = (str)=>{
let r = []
for (let i=0; i<str.length; i++) {
r.push(str.charCodeAt(i).toString(2));
}
return parseInt(r.join(""));
}

Categories

Resources