Let's say I have a string as such:
var text = "Hi ππ";
I want to store this text in a database and wish to convert the emoji's to unicode.
My current solution is to convert the string to an array. Then convert each character to unicode.
function toUnicode(text){
var arr = Array.from(text);
var unicodeArr = [];
for (let i = 0; i < arr.length; i++) {
var unicode = arr[i].codePointAt(0).toString(16);
unicodeArr.push(unicode);
}
return JSON.stringify(unicodeArr);
}
Here are the output when I run the code:
var text = "Hi ππ";
var unicodeArr = toUnicode(text);
console.log(unicodeArr); //["48","69","20","1f602","1f602"]
The only issue is that I'm not sure how to convert this back to a whole string.
Is there a much more easy solution to store this var text = "Hi ππ"; in a Database?
I modified your "toUnicode" function to return an array of numbers and not a jsonified array of number.toString, so I didn't have to parse it all again to unpack it. Give this a try:
function toUnicode(text){
return Array.from(text).map(char => char.codePointAt(0));
}
function fromUnicode(unicode) {
return unicode.map(num => String.fromCodePoint(num)).join("");
}
var text = "Hi ππ";
var unicodeArr = toUnicode(text);
var backToString = fromUnicode(unicodeArr);
console.log(text, unicodeArr, backToString);
You can convert to base64 which is platform agnostic:
var text = "Hi ππ";
const b64 = btoa(unescape(encodeURIComponent(text)));
const txt = decodeURIComponent(escape(atob(b64)));
console.log(b64);
console.log(txt);
Related
I am new for javascript, I have a one long string i want to split after 3rd commas and change diffferent format. If you are not understand my issues. Please see below example
My string:
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
I want output like this:(Each item should be in next line)
Idly(3 Pcs) - 10 = 200
Ghee Podi Idly - 10 = 300
How to change like this using JavaScript?
Just copy and paste it. Function is more dynamic.
Example Data
var testData = "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
Function
function writeData(data){
data = data.split(',');
var tempLine='';
for(var i=0; i<data.length/3; i++) {
tempLine += data[i*3+1] + ' - ' + data[i*3] + ' = ' + data[i*3+2] + '\n';
}
alert(tempLine);
return tempLine;
}
Usage
writeData(testData);
Use split method to transform the string in a array and chunk from lodash or underscore to separate the array in parts of 3.
// A custom chunk method from here -> http://stackoverflow.com/questions/8495687/split-array-into-chunks
Object.defineProperty(Array.prototype, 'chunk_inefficient', {
value: function(chunkSize) {
var array=this;
return [].concat.apply([],
array.map(function(elem,i) {
return i%chunkSize ? [] : [array.slice(i,i+chunkSize)];
})
);
}
});
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
var arr = test.split(',');
var arr = arr.chunk_inefficient(3);
arr.forEach(function (item) {
console.log(item[1]+' - '+item[0]+' = '+item[2]);
});
You can use split to split the string on every comma. The next step is to iterate over the elements, put the current element into a buffer and flush the buffer if it's size is three. So it's something like:
var tokens = test.split(",");
var buffer = [];
for (var i = 0; i < tokens.length; i++) {
buffer.push(tokens[i]);
if (buffer.length==3) {
// process buffer here
buffer = [];
}
}
If you have fix this string you can use it otherwise validate string.
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
var test2= test.split(",");
var temp_Str= test2[1]+' - '+test2[0]+' = '+test2[2]+'\n';
temp_Str+= test2[4]+'-'+test2[3]+' = '+test2[5];
alert(temp_Str);
I need to extract a particular string in javascript of format: βSTATE: ip reachableβ from another set of string I have as input.
From the extracted string, I need to extract both the numbers.
I have done so far is:
var str=<the input value>;
if(str.contains("STATE"))
{
var str = str.substring(str.indexOf("STATE"), string.indexOf("reachable");
}
I am finding difficulty in how to extract the numbers.
I don't really understand what are the 'numbers', but I tried that :
var str= "lorem ipsum STATE: 10.0.5.2 120.30.66.8 test ... blabla bla";
str = str.slice(str.indexOf("STATE"), str.length);
var tab = str.split(" ");
var num1 = tab[1];
var num2 = tab[2];
Use a regular expression...something like this:
var test = "STATE 10.0.0.18 192.168.42.9 reachable";
var ips = test.match(/(\d+\.\d+\.\d+\.\d+)/g);
for (i = 0; i < ips.length; i++) {
document.write(ips[i]);
document.write("<br>");
}
If you are sure about the pattern in the string, you can use below code :
var str = "STATE 10.0.0.18 192.168.42.9 reachable";
if (str.indexOf("STATE") >= 0) {
var str = str.substring(str.indexOf("STATE ")+6, str.indexOf(" reachable"));
var arrIP = str.split(" ");
for (i = 0; i < arrIP.length; i++) {
alert(arrIP[i]);
}
}
jsfiddle : https://jsfiddle.net/nikdtu/4nx50b81/
I have 2 strings with some chars. One of them is with "mashed" characters, and the other one is with ordered characters which have some sense. For example:
wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!
Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT
So as you may see - the first one have equivalent of symbols which are the same for the equal symbol in the second one.
And the task is - to create somehow kind of alphabet from them, because I have third one string wich have to be "decoded". (wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!).
And the tricky part here is - that if I'm pretty sure for the first two strings that they're absolutely equal like a number of chars, so about the new one - is completely different number of symbols, but they consisting in the "alphabet"
And here is my current code for creation of the "alphabet":
var enc = "wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!";
var dec = "Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT";
var newenc = "wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!";
var myenc = {};
var mynewenc = {};
for (i = 0; i < enc.length; i+=1) {
var encoded = new Array(enc[i]);
var decoded = new Array(dec[i]);
myenc[enc[i]] = dec[i];
};
console.log(myenc);
And now - how I have to decode, the new one string, using this "alphabet"?
var enc = "wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!";
var dec = "Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT";
var newenc = "wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!";
function make_dictionary(enc, dec){
o = new Object();
if(enc.length == dec.length){
for(i=0; i<enc.length; i++){
o[enc[i]] = dec[i];
}
}
else{
console.log('error');
}
return o;
}
function translate(newenc, dictionary, fill){
var newstring = '';
for(i=0; i<newenc.length; i++){
if(typeof dictionary[newenc[i]] !== 'undefined'){
newstring += dictionary[newenc[i]];
}
else{
newstring += fill;
}
}
return newstring;
}
var d = make_dictionary(enc, dec);
console.log(d);
var string = translate(enc, d, '_');
console.log(string);
var string = translate(newenc, d, '_');
console.log(string);
Here's one way that you can approach it (as I understand the question):
// Create your dictionary
var dict = {};
var enc = "wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!".split('');
var dec = "Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT".split('');
// Populate your dictionary
for (var i = 0; i < enc.length; i++) {
dict[enc[i]] = dec[i];
}
// You can use your dictionary like this
var newenc = "wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!".split('');
// Returns your translated string
newenc.map(function(e) {
return dict[e];
}).join('');
However for this method you'll have to deal with characters that are defined in newenc that are not defined in your enc (such as T). I tried to do the best I could given the situation and rules that you've described, hope this helps!
If I understand well, you can try using this code.
It is finding the appropriate encoded letter in your enc variable and if the letter is found, it is replacing it with the corresponding letter from your dec variable.
var enc = "wvEr2JmJUs2JRr:7Fob9WIB8mSOA?w0s2E:7-f/-G/N-.f7jN:Mi:.CDfGX7tn!";
var dec = "Identification: zpE?bkHlfYS-hIDate: 07/08/2057 12:34:56.789 CGT";
var newenc = "wvEr2JmJUs2JRr:7a1AJvvHvAmRRWsxWsFAvJvAJAaoE88A2?s2AxJ1?290s2E:7-f/-G/N-.f7jN:MC:ifDCGN7tn!";
for (i = 0; i < newenc.length; i++) {
for (j = 0; j < enc.length; j++) {
if (enc[j] == newenc[i])
newenc[i] = dec[j];
}
};
console.log(newenc);
At the end your variable newenc may contain your decoded string.
Here is how I compress binary string (char codes above 255) with pako:
var charData = xhr.responseText.split('').map(function(x){return x.charCodeAt(0);});
var binData = new Uint8Array(charData);
var data = pako.deflate(binData, {level:"9"});
Here is how I decompress data back:
var data2 = pako.inflate(xhr.responseText);
Now, how can I get original string in JavaScript from this object?
I tried methods like this:
A.
pako.inflate(xhr.responseText, {to:"string"});
B.
String.fromCharCode.apply(null, data2);
C.
for (var i = 0, l = data2.length; i < l; i++)
{
result += String.fromCharCode(parseInt(array[i], 2));
}
All of these methods bring different data as JavaScript string than original.
When I save decompressed pako.inflate(xhr.responseText) to a file (using functions with a.download) then dempressed file has exactly the same bytes as original file (so compression and decompression works correctly, without any byte modification).
I am just trying to do the same and found a way to convert Object to binary string and vice versa. I just create a two function that converts JSON Object to Binary String and Binary String to JSON Object viz. covertObjectToBinary and convertBinaryToObject.
let obj = {a:1}
function covertObjectToBinary(obj) {
let output = '',
input = JSON.stringify(obj) // convert the json to string.
// loop over the string and convert each charater to binary string.
for (i = 0; i < input.length; i++) {
output += input[i].charCodeAt(0).toString(2) + " ";
}
return output.trimEnd();
}
function convertBinaryToObject(str) {
var newBin = str.split(" ");
var binCode = [];
for (i = 0; i < newBin.length; i++) {
binCode.push(String.fromCharCode(parseInt(newBin[i], 2)));
}
let jsonString = binCode.join("");
return JSON.parse(jsonString)
}
console.log('covertObjectToBinary =>', covertObjectToBinary(obj))
console.log('convertBinaryToObject =>', convertBinaryToObject(covertObjectToBinary(obj)))
Is there by any chance a built-in javascript function that parses:
var string = '[2,1,-4]';
var multiString = '[[-3,2,-1][2,-3,2][1,-1,3]]';
to
var array = [2,1,-4];
var multiArray = [[-3,2,-1],[2,-3,2],[1,-1,3]];
or do I have to write a custom function for this?
Assuming your correct your multiString to the correct format
(ie. '[[-3,2,-1],[2,-3,2],[1,-1,3]]')
Then yes.
array = JSON.parse(string);
multiArray = JSON.parse(multiString);
For completeness, you can use eval:
var s = '[1,2,3]';
var a = eval(s);
however if the string is valid JSON, then as Niet suggested, JSON.parse is a much better solution.
If you want to do this on your own, it can be done using substring and split. A possible solution could look like this:
var multiString = '[[-3,2,-1][2,-3,2][1,-1,3]]';
var string = '[2,1,-4]';
function parse(input) {
var s = input;
// remove leading [ and trailing ] if present
if (input[0] == "[") {
s = input.substring(0, input.length);
}
if (input[input.length] == "]") {
s = s.substring(input.length-1, 1);
}
// create an arrray, splitting on every ,
var items = s.split(",");
return items;
}
// items is now an array holding 2,-1,4
var items = parse(string);
You can then split the bigger string into smaller chunks and apply the function to each part using array.map:
function parseAOfA(input) {
var s = input.substring(0, input.length).substring(input.length-1, 1);
s = s.substring(0, s.length).substring(s.length-1, 1);
s = s.split("][");
var items = s.map(parse);
return items;
}
var items = parseAOfA(multiString);