Cleaning string in JS from UTF-32 characters - javascript

I need to clean characters encoded in UTF-32 from string in JS, like "💣".
I tried to use code:
str.replace(/[^\u0000-\uFFFF]/gi, '')
But it isn't work.

For clean message I used
function fixedCharCodeAt(str, idx) {
var code = str.charCodeAt(idx);
if (0xD800 <= code && code <= 0xDBFF) {
// Upper auxiliary char
var hi = code;
var low = str.charCodeAt(idx+1);
return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
}
if (0xDC00 <= code && code <= 0xDFFF) {
// Lower auxiliary symbol
var hi = str.charCodeAt(idx-1);
var low = code;
return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
}
return code;
}
and
function cleaningMsgFromBreakingSymb(message_old) {
var new_message = "";
for (var i = 0, len = message_old.length; i < len; i++) {
if (fixedCharCodeAt(message_old, i) < 65535){
new_message += message_old[i];
};
};
return new_message;
}

Related

Coding a hidden message in image

I want to code a hidden message in image using js, but don`t know how this works. I have been searching for some algorithm but dont found one. Can some one explain how to encode message in image using js?
Use this library https://www.peter-eigenschink.at/projects/steganographyjs/
It will allow you to hide text into images
EDIT - Adding the encoding code from the link
Cover.prototype.encode = function(message, image, options) {
// Handle image url
if(image.length) {
image = util.loadImg(image);
} else if(image.src) {
image = util.loadImg(image.src);
} else if(!(image instanceof HTMLImageElement)) {
throw new Error('IllegalInput: The input image is neither an URL string nor an image.');
}
options = options || {};
var config = this.config;
var t = options.t || config.t,
threshold = options.threshold || config.threshold,
codeUnitSize = options.codeUnitSize || config.codeUnitSize,
prime = util.findNextPrime(Math.pow(2,t)),
args = options.args || config.args,
messageDelimiter = options.messageDelimiter || config.messageDelimiter;
if(!t || t < 1 || t > 7) throw new Error('IllegalOptions: Parameter t = " + t + " is not valid: 0 < t < 8');
var shadowCanvas = document.createElement('canvas'),
shadowCtx = shadowCanvas.getContext('2d');
shadowCanvas.style.display = 'none';
shadowCanvas.width = options.width || image.width;
shadowCanvas.height = options.height || image.height;
if(options.height && options.width) {
shadowCtx.drawImage(image, 0, 0, options.width, options.height );
} else {
shadowCtx.drawImage(image, 0, 0);
}
var imageData = shadowCtx.getImageData(0, 0, shadowCanvas.width, shadowCanvas.height),
data = imageData.data;
// bundlesPerChar ... Count of full t-bit-sized bundles per Character
// overlapping ... Count of bits of the currently handled character which are not handled during each run
// dec ... UTF-16 Unicode of the i-th character of the message
// curOverlapping ... The count of the bits of the previous character not handled in the previous run
// mask ... The raw initial bitmask, will be changed every run and if bits are overlapping
var bundlesPerChar = codeUnitSize/t >> 0,
overlapping = codeUnitSize%t,
modMessage = [],
decM, oldDec, oldMask, left, right,
dec, curOverlapping, mask;
var i, j;
for(i=0; i<=message.length; i+=1) {
dec = message.charCodeAt(i) || 0;
curOverlapping = (overlapping*i)%t;
if(curOverlapping > 0 && oldDec) {
// Mask for the new character, shifted with the count of overlapping bits
mask = Math.pow(2,t-curOverlapping) - 1;
// Mask for the old character, i.e. the t-curOverlapping bits on the right
// of that character
oldMask = Math.pow(2, codeUnitSize) * (1 - Math.pow(2, -curOverlapping));
left = (dec & mask) << curOverlapping;
right = (oldDec & oldMask) >> (codeUnitSize - curOverlapping);
modMessage.push(left+right);
if(i<message.length) {
mask = Math.pow(2,2*t-curOverlapping) * (1 - Math.pow(2, -t));
for(j=1; j<bundlesPerChar; j+=1) {
decM = dec & mask;
modMessage.push(decM >> (((j-1)*t)+(t-curOverlapping)));
mask <<= t;
}
if((overlapping*(i+1))%t === 0) {
mask = Math.pow(2, codeUnitSize) * (1 - Math.pow(2,-t));
decM = dec & mask;
modMessage.push(decM >> (codeUnitSize-t));
}
else if(((((overlapping*(i+1))%t) + (t-curOverlapping)) <= t)) {
decM = dec & mask;
modMessage.push(decM >> (((bundlesPerChar-1)*t)+(t-curOverlapping)));
}
}
}
else if(i<message.length) {
mask = Math.pow(2,t) - 1;
for(j=0; j<bundlesPerChar; j+=1) {
decM = dec & mask;
modMessage.push(decM >> (j*t));
mask <<= t;
}
}
oldDec = dec;
}
// Write Data
var offset, index, subOffset, delimiter = messageDelimiter(modMessage,threshold),
q, qS;
for(offset = 0; (offset+threshold)*4 <= data.length && (offset+threshold) <= modMessage.length; offset += threshold) {
qS=[];
for(i=0; i<threshold && i+offset < modMessage.length; i+=1) {
q = 0;
for(j=offset; j<threshold+offset && j<modMessage.length; j+=1)
q+=modMessage[j]*Math.pow(args(i),j-offset);
qS[i] = (255-prime+1)+(q%prime);
}
for(i=offset*4; i<(offset+qS.length)*4 && i<data.length; i+=4)
data[i+3] = qS[(i/4)%threshold];
subOffset = qS.length;
}
// Write message-delimiter
for(index = (offset+subOffset); index-(offset+subOffset)<delimiter.length && (offset+delimiter.length)*4<data.length; index+=1)
data[(index*4)+3]=delimiter[index-(offset+subOffset)];
// Clear remaining data
for(i=((index+1)*4)+3; i<data.length; i+=4) data[i] = 255;
imageData.data = data;
shadowCtx.putImageData(imageData, 0, 0);
return shadowCanvas.toDataURL();
};

count 9's from 1 to n - 5kyu Kata

I am working on this kata https://www.codewars.com/kata/count-9-s-from-1-to-n/train/javascript
and i have written this code for it, but its not working. This question is similar to this one Count the number of occurrences of 0's in integers from 1 to N
but it is different because searching for 9's is practically very different to searching for 0's.
think part of the problem with this code is that it takes too long to run...
any advice appreciated!
function has9(n) {
var nine = [];
var ninearr = n.toString().split('');
for (var j = 0; j < ninearr.length; j++) {
if (ninearr[j] == '9') {
nine.push(ninearr[j]);
}
}
return nine.length;
}
function number9(n) {
var arr = [];
var arrnew = [];
for (var i = 0; i <= n; i++) {
arr.push(i);
}
for (var l = 0; l < arr.length; l++) {
arrnew.push(has9(l));
}
var sum = arrnew.reduce((a, b) => a + b, 0);
return sum;
}
Why not a regex based solution? (Too slow as well?)
const count9s = num => num.toString().match(/9/g).length
console.log(count9s(19716541879)) // 2
console.log(count9s(919191919191919)) // 8
console.log(count9s(999)) // 3
console.log(count9s(999999)) // 6
I have taken the above hint and completely re written the code, which I now feel should work, and it does for most inputs, but codewars is saying it fails on some of them. any ideas why?
function nines(n){
if(n>=100){
var q= Math.floor(n/100);
var nq= q * 20;
var r = (n%100);
var s = Math.floor(r/9);
if (r<=90){
return s + nq;
}
if (r == 99){
return 20 + nq;
}
if (90 < r < 100 && r!= 99){
var t = (r-90);
return nq + s + t;
}
}
if (n<100){
if (n<=90){
var a = Math.floor(n/9);
return a ;
}
if (n == 99){
return 20
}
if (90 < n < 100 && n!= 99){
var c = (n-90);
return 10 + c;
}
}
}
=== UPDATE ===
I just solved your kata using
function number9Helper(num) {
var pow = Math.floor(Math.log10(num));
var round = Math.pow(10, pow);
var times = Math.floor(num / round);
var rest = Math.abs(num - (round * times));
var res = pow * (round==10 ? 1 : round / 10) * times;
if (num.toString()[0] == '9') res += rest;
if (rest < 9) return res;
else return res + number9Helper(rest);
}
function number9(num) {
var res = number9Helper(num);
res = res + (num.toString().split('9').length-1);
return res;
}
== Function below works but is slow ===
So, could something like this work for you:
for (var nines=0, i=1; i<=n; i++) nines += i.toString().split('9').length-1;
Basically, there are many way to achieve what you need, in the end it all depends how do you want to approach it.
You can test it with
function nines(n) {
for (var nines=0, i=1; i<=n; i++) nines += i.toString().split('9').length-1;
return nines;
}
function number9(n) {
if (n < 8) {
return 0
};
if (n === 9) {
return 1
};
if (n > 10) {
let str = ''
for (let i = 9; i <= n; i++) {
str += String(i)
}
return str.match(/[9]/g).length
}
}

Problems with Shift Cipher (ROT-13) function and String.fromCharCode in JS

Trying to get a JS function to work that shifts the individual characters in a string by a set amount (and then returns the new "shifted" string). I'm using ROT-13 (so A-M are shifted down 13 characters and N-Z are shifted up 13 characters).
The trouble lies with this piece of code:
if (arr[i] <= 77) {
finalStr += String.fromCharCode(arr[i] + 13);
This code should shift E to R.
E (69) + 13 = R (82)
However, the characters in the returned string that should be shifted down 13 spaces return as weird symbols.
"FᬁEE಍C᧕DE಍CAMᨹ"
function rot13(str) {
var newStr = "";
var finalStr = "";
for (i = 0, j = str.length; i < j; i++) {
newStr += str.charCodeAt(i);
newStr += " ";
}
var arr = newStr.split(" ");
arr.pop();
for (i = 0, j = arr.length; i < j; i++) {
if (arr[i] !== 32) {
if (arr[i] <= 77) {
finalStr += String.fromCharCode(arr[i] + 13);
}
else {
finalStr += String.fromCharCode(arr[i] - 13);
}
}
}
return finalStr;
}
rot13("SERR PBQR PNZC");
The problem doesn't appear to be what you identified but rather your handling of the conversion from characters to character codes. Simplifying and cleaning up your conversioin logic seems to fix the problem:
function rot13(str) {
var arr = new Array();
for (var i = 0; i < str.length; i++) {
arr[arr.length] = str.charCodeAt(i);
}
var finalStr = "";
for (var i = 0; i < arr.length; i++) {
if (arr[i] !== 32) {
if (arr[i] <= 77) {
finalStr += String.fromCharCode(arr[i] + 13);
} else {
finalStr += String.fromCharCode(arr[i] - 13);
}
} else {
finalStr += String.fromCharCode(32);
}
}
return finalStr;
}
rot13("SERR PBQR PNZC");
Which returns "FREE CODE CAMP".
And just to blow your mind a little more:
var rot13=function(str){
return str.split('')
.map(function(ch){
var v=ch.charCodeAt(0);
return String.fromCharCode(v > 77 ? v-13 : v+13);
})
.join('');
};
UPDATE - Version that handles both upper and lower-cased letters
var rot13 = function(s){
return s.split('').map(function(c){
var v=c.toLowerCase().charCodeAt(0);
if(v<97 || v>122) return c;
var t = v>=96,
k = (v - 96 + 12) % 26 + 1;
return String.fromCharCode(k + (t ? 96 : 64));
}).join('');
};
rot13('SERR PBQR PNZC') // => FREE CODE CAMP
Just had an idea : why not doing it on one line only ? And by the way, I looked at the Free Code Camp challenge and u have to bypass all non alphanumerical characters. Here it is :
function rot13(str) { // LBH QVQ VG!
return str.split('').map(function(letter){
return letter.match(new RegExp(/\W/i)) ? letter : (letter.charCodeAt(0) <= 77 ? String.fromCharCode(letter.charCodeAt(0) + 13) : String.fromCharCode(letter.charCodeAt(0) - 13));
}).join('');
}
// Change the inputs below to test
rot13("SERR PBQR PNZC"); // FREE CODE CAMP
TADAAAAH :-)
Here is the pen : http://codepen.io/liorchamla/pen/mPwdEz/
Hope u will like it and also hope you will try hard to understand this !
Happy Free Code Camp to all !

Convert excel column alphabet (e.g. AA) to number (e.g., 25)

In my grid the column headers are named A,B,C...,AA,AB,AC,...etc like an excel spreadsheet. How can I convert the string to number like: A => 1, B => 2, AA => 27
Try:
var foo = function(val) {
var base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', i, j, result = 0;
for (i = 0, j = val.length - 1; i < val.length; i += 1, j -= 1) {
result += Math.pow(base.length, j) * (base.indexOf(val[i]) + 1);
}
return result;
};
console.log(['A', 'AA', 'AB', 'ZZ'].map(foo)); // [1, 27, 28, 702]
solution 1: best performance and browser compatibility
// convert A to 1, Z to 26, AA to 27
function lettersToNumber(letters){
var chrs = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ', mode = chrs.length - 1, number = 0;
for(var p = 0; p < letters.length; p++){
number = number * mode + chrs.indexOf(letters[p]);
}
return number;
}
solution 2: best performance and compatibility and shorter code (Recommended)
// convert A to 1, Z to 26, AA to 27
function lettersToNumber(letters){
for(var p = 0, n = 0; p < letters.length; p++){
n = letters[p].charCodeAt() - 64 + n * 26;
}
return n;
}
solution 3: short code (es6 arrow function)
// convert A to 1, Z to 26, AA to 27
function lettersToNumber(letters){
return letters.split('').reduce((r, a) => r * 26 + parseInt(a, 36) - 9, 0);
}
test:
['A', 'Z', 'AA', 'AB', 'ZZ','BKTXHSOGHKKE'].map(lettersToNumber);
// [1, 26, 27, 28, 702, 9007199254740991]
lettersToNumber('AAA'); //703
Here's a quick example of the code you should implement.
This will work with any given number of letters.
function letterToNumbers(string) {
string = string.toUpperCase();
var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', sum = 0, i;
for (i = 0; i < string.length; i++) {
sum += Math.pow(letters.length, i) * (letters.indexOf(string.substr(((i + 1) * -1), 1)) + 1);
}
return sum;
}
i just wrote a junk yard f##$ snippet... need to be optimized.. :)
charToNum = function(alpha) {
var index = 0
for(var i = 0, j = 1; i < j; i++, j++) {
if(alpha == numToChar(i)) {
index = i;
j = i;
}
}
console.log(index);
}
numToChar = function(number) {
var numeric = (number - 1) % 26;
var letter = chr(65 + numeric);
var number2 = parseInt((number - 1) / 26);
if (number2 > 0) {
return numToChar(number2) + letter;
} else {
return letter;
}
}
chr = function (codePt) {
if (codePt > 0xFFFF) {
codePt -= 0x10000;
return String.fromCharCode(0xD800 + (codePt >> 10), 0xDC00 + (codePt & 0x3FF));
}
return String.fromCharCode(codePt);
}
charToNum('A') => returns 1 and charToNum('AA') => returns 27;
// Given Column to Number
function colToNumber(str) {
let num = 0
let i = 0
while (i < str.length) {
num = str[i].charCodeAt(0) - 64 + num * 26;
i++;
}
return num;
}
//Given Number to Column name
function numberToCol(num) {
let str = '', q, r;
while (num > 0) {
q = (num-1) / 26;
r = (num-1) % 26
num = Math.floor(q)
str = String.fromCharCode(65 + r) + str;
}
return str;
}
I rewrote Yoshi's answer in a more verbose form that explains better how it works and is easier to port to other languages:
var foo = function(val) {
var base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var baseNumber = base.length;
var runningTotal = 0;
var characterIndex = 0;
var indexExponent = val.length - 1;
while( characterIndex < val.length ){
var digit = val[characterIndex];
var digitValue = base.indexOf(digit) + 1;
runningTotal += Math.pow(baseNumber, indexExponent) * digitValue;
characterIndex += 1
indexExponent -= 1
}
return runningTotal;
};
console.log(['A', 'AA', 'AB', 'ZZ'].map(foo)); // [1, 27, 28, 702]
Public Function ColLet2Num(Letras As String)
'RALONSO MAYO 2017
'A-> 1
'OQ ->407
'XFD->16384
Dim UnChar As String
Dim NAsc As Long
Dim F As Long
Dim Acum As Long
Dim Indice As Long
Letras = UCase(Letras)
Acum = 0
Indice = 0
For F = Len(Letras) - 1 To 0 Step -1
UnChar = Mid(Letras, F + 1, 1)
NAsc = Asc(UnChar) - 64
Acum = Acum + (NAsc * (26 ^ Indice))
Indice = Indice + 1
Next
If Acum > 16384 Then
MsgBox "La celda máxima es la XFD->16384", vbCritical
End If
ColLet2Num = Acum
End Function
const getColumnName = (columnNumber) => {
let columnName = "";
const alphabets = "abcdefghijklmnopqrstuvwxyz".toUpperCase();
while (columnNumber > 0) {
const rem = columnNumber % 26;
if (rem === 0) {
columnName += "Z";
columnNumber = columnNumber / 26 - 1;
} else {
columnName += alphabets[rem - 1];
columnNumber = Math.floor(columnNumber / 26);
}
}
return columnName.split("").reverse().join("");
};
console.log(getColumnName(27));
A good readability and performance example:
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// create dict to O(1) access to letter number
const dict = Object.fromEntries(letters.split('').map((it, index) => [it, index + 1]));
function toNumber(col) {
return col
.toUpperCase()
.split('')
.reduce((acc, letter, index) => acc + Math.pow(letters.length, col.length - (index + 1)) * dict[letter], 0);
}
Highly inspired by the different solutions put forth on this page
//fixed the one taken from here
function colToNumber(str: string): number {
var num = 0
for (var i = 0; i < str.length; i++) {
const current_letter = str.charCodeAt(i) - 64
const current_char = str[i]
if (i == str.length - 1) {
num += current_letter
} else {
var current = current_letter * Math.pow(26, str.length - i - 1)
num += current
}
}
return num;
}
//Given Number to Column name (taken from here)
function numberToCol(num: number) {
var str = '', q: number, r: number;
while (num > 0) {
q = (num - 1) / 26;
r = (num - 1) % 26
num = Math.floor(q)
str = String.fromCharCode(65 + r) + str;
}
return str;
}
function test_both() {
const dic = new Map<number, string>()
dic.set(1,"A")
dic.set(10,"J")
dic.set(13,"M")
dic.set(33,"AG")
dic.set(63,"BK")
dic.set(66,"BN")
dic.set(206,"GX")
dic.set(502,"SH")
dic.set(1003,"ALO")
dic.set(100,"CV")
dic.set(10111,"NXW")
dic.set(10001,"NTQ")
dic.set(9002,"MHF")
dic.set(5002,"GJJ")
dic.set(3002,"DKL")
dic.set(16384,"XFD")
for (var key of dic.keys()) {
const expected_a1 = dic.get(key) || ""
//console.log(`${ key }, ${ expected_a1 } `)
var actual = numberToCol(key)
var actual_num = colToNumber(expected_a1)
if (actual.localeCompare(expected_a1) != 0) {
console.error(`key = ${key} == expected=${expected_a1} actual = ${actual} `)
}
if (actual_num != key) {
console.error(`expected = ${expected_a1} key = ${key} == actual = ${actual_num} `)
}
}
}

How to write a base32_decode in JavaScript?

I'm trying to create the equivalent of PHP's unpack. I've noticed the project PHPJS doesn't have it. I need it for the implementation of base32_encode and base32_decode (using Crockford's alphabet '0123456789ABCDEFGHJKMNPQRSTVWXYZ').
I couldn't find it anywhere and judging from it's counterpart, PHPJS's pack function I doubt my version will be complete and bug free any time soon.
base32tohex = (function() {
var dec2hex = function(s) {
return (s < 15.5 ? "0" : "") + Math.round(s).toString(16)
}
, hex2dec = function(s) {
return parseInt(s, 16)
}
, base32tohex = function(base32) {
for (var base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", bits = "", hex = "", i = 0; i < base32.length; i++) {
var val = base32chars.indexOf(base32.charAt(i).toUpperCase());
bits += leftpad(val.toString(2), 5, "0")
}
for (i = 0; i + 4 <= bits.length; i += 4) {
var chunk = bits.substr(i, 4);
hex += parseInt(chunk, 2).toString(16)
}
return hex
}
, leftpad = function(str, len, pad) {
return len + 1 >= str.length && (str = new Array(len + 1 - str.length).join(pad) + str),
str
};
return base32tohex;
}
)()

Categories