how to decode string in javascript? - javascript

I am trying to decode my string using JavaScript. Here is my code on JSBin.
decordMessage('oppeeennnn','1234');
function decordMessage(m,k) {
var msg = m.split('');
var keysplit = k.split('');
var str ='';
var j =0
for (var i=0;i<msg.length;){
str += msg[i];
if(j < keysplit.length -2 &&i < keysplit.length && keysplit[j]){
i = i + parseInt(keysplit[j]);
j++;
}
console.log(i +"i")
console.log(str);
}
console.log("after");
console.log(str);
}
I make a function in which message and key is passed.
Expected output :: open
Actually string charters are repeated in input message (encrypted message) using key. So I need to decode the message.

You forgot to put a break in the else condition, that's why it was looping infinitely till it ran out of memory. Run it in a browser and the tab will crash:
decordMessage('oppeeennnn','1234');
function decordMessage(m,k) {
var msg = m.split('');
var keysplit = k.split('');
var str ='';
var j =0
for (var i=0;i<msg.length;){
str += msg[i];
if(j < keysplit.length &&i < keysplit.length && keysplit[j]){
i = i + parseInt(keysplit[j]);
j++;
}
else
break;
}
console.log("after");
console.log(str); // prints open
}
By the way, a better way to write the loop would be:
function decordMessage(m,k) {
var msg = m.split('');
var keysplit = k.split('');
var str = '';
var j = 0, i = 0;
while (j < keysplit.length
&& i < msg.length) {
str += msg[i];
i += parseInt(keysplit[j]);
j++;
}
console.log(str)
}

This may helps you.
decordMessage('oppeeennnn', '1234');
function decordMessage(m, k) {
var arr = m.split("");
uniqueArray = arr.filter(function(item, pos) {
return arr.indexOf(item) == pos;
});
console.log(uniqueArray.join(""));
}
Assuming encryption logic goes as 123456....
Sample here

Related

How can I use a variable in String.fromCharCode()?

I am trying to get the code below to convert the unicode into a string but have no luck, please help?
function rot13(str) {
var message = "";
for (var i = 0; i < str.length; i++) {
message += str.charCodeAt(i) + " ";
}
message = message.split(" ").filter(Boolean).join(",");
return String.fromCharCode(message);
}
console.log(rot13("Hello World"))
fromCharCode("1,1,1,1") is not the same thing as fromCharCode(1,1,1,1) you need to use apply with an array.
function rot13(str) {
var message = "";
for (var i = 0; i < str.length; i++) {
message += str.charCodeAt(i) + " ";
}
message = message.split(" ").filter(Boolean);
return String.fromCharCode.apply(String, message);
}
console.log(rot13("Hello World"))
You want something like this:
http://buildingonmud.blogspot.com/2009/06/convert-string-to-unicode-in-javascript.html
function toUnicode(theString) {
var unicodeString = '';
for (var i = 0; i < theString.length; i++) {
var theUnicode = theString.charCodeAt(i).toString(16).toUpperCase();
while (theUnicode.length < 4) {
theUnicode = '0' + theUnicode;
}
theUnicode = '\\u' + theUnicode;
unicodeString += theUnicode;
}
return unicodeString;
}
console.log(toUnicode("Hello World"));

replace odd and even occurence with html javascript

I am trying to replace ` ticks with html code in a string.
var str = "this `code` and `here`"
my expected output
"this code and here"
What i am trying to do is below
.
get the positions with ticks in a string
replace those ticks with span html based on odd and even occurence.
not sure, i couldnt get expected and my browser gets hang. and
when i debug it. i see there is no index for string to replace.
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
var pos = [];
for (var i = 0; i < str.length; i++) {
if (str[i] === "`") {
pos.push(i);
}
}
if (pos.length > 1) {
for (var j = pos.length; j > 0; j--) {
var index = pos[j];
var spanHtml = '';
if (j % 2 == 0) {
spanHtml = "<span class='code'>"
} else {
spanHtml = "</span>";
}
str = str.replaceAt(index, spanHtml);
}
}
You can use String.prototype.replace() with RegExp
/(`\w+`)/g
String.prototype.slice() with parameters 1, -1 to slice string within backtick
`
characters
var str = "this `code` and `here`";
var res = str.replace(/(`\w+`)/g, function(match) {
return "<span class='code'>" + match.slice(1, -1) + "</span>"
});
document.body.insertAdjacentHTML("beforeend", res);
.code {
background: turquoise;
}
scope of var i is wider then you think, so pos.push(i) will have them all same at the end
replaceAt appends incorrect ending
replaceAt shifts rest of the string invalidating positions you found
I believe you wanted something along these lines:
var str = "this `code` and `here`"
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+1);
}
var pos = [];
var count = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] === "`") {
var index = i;
var spanHtml = '';
if (count % 2 == 0) {
spanHtml = "<span class='code'>"
} else {
spanHtml = "</span>";
}
count++;
str = str.replaceAt(index, spanHtml);
i+= spanHtml.length -1; // correct position to account for the replacement
}
}
console.log(str)
Use the JavaScript replace method.
var str = "this `code` and `here`";
var newStr = str.replace("`", "");

Javascript For Loop: Assignment to character not working

I was writing a test function to capitalize each word in a sentence. I ended up solving it; however, one of my first attempts to solve the problem didn't work when I thought it would.
function capSentence(str) {
var strArray = str.split(" ");
var answer = '';
var temp = '';
for(var i = 0; i < strArray.length; i++){
strArray[i][0] = strArray[i][0].toUpperCase();
answer += strArray[i];
if(i !== strArray.length-1){
answer += ' ';
}
}
return answer;
}
capSentence("this is a test");
I thought the above code would output "This Is A Test", but instead it outputs "this is a test".
strArray[i][0] = strArray[i][0].toUpperCase();
doesn't seem to have any affect. Why is that?
#thefourtheye's comment is correct. You need to build a new string.
function capSentence(str) {
var strArray = str.split(" ");
var answer = '';
var temp = '';
for(var i = 0; i < strArray.length; i++){
answer += strArray[i][0].toUpperCase();
answer += strArray[i].slice(1,strArray[i].length);
if(i !== strArray.length-1){
answer += ' ';
}
}
return answer;
}
Strings are immutable in Javascript. That's why you are not able to change the value of the strArray.
But you can do in this way:
function capSentence(str) {
strArray = str.split(" ");
console.log(strArray);
var answer = '';
var temp = '';
for(var i = 0; i < strArray.length; i++){
for (var j = 0; j< strArray[i].length; j++) {
if(j==0) {
temp = strArray[i][j].toUpperCase();
} else {
temp+=strArray[i][j];
}
}
answer += temp;
if(i !== strArray.length-1){
answer += ' ';
}
}
return answer;
}
This will retrun "This Is A Test"
Try this simple snippet,
function capSentence(str) {
var strArray = str.split(" ");
var answer = '';
var temp = '';
for(var i = 0; i < strArray.length; i++){
answer += (strArray[i].substring(0,1)).toUpperCase()+strArray[i].substring(1);
if(i !== strArray.length-1){
answer += ' ';
}
}
return answer;
}

Reusing simple Javascript Function

I'm new to JS and would like to know how to refactor this simple code so that I can pass in strings to count the number of "e" in a string.
function countE() {
var count = 0;
var str = "eee";
var charLength = str.length;
for (i =0; i <= charLength; i++){
if(str.charAt(i) == "e"){
count++;
}
}
console.log(count);
}
I would like to execute this function where I can do something like this:
countE('excellent elephants');
which would log 5.
function countE(str) {
if(typeof(str)==='undefined') str = 'eee';
var count = 0;
var charLength = str.length;
for (i =0; i <= charLength; i++){
if(str.charAt(i) == "e"){
count++;
}
}
console.log(count);
}
If you want to make your function body shorter, you can do the following:
function countE(str) {
return str.match(/e/g).length;
}
And even more sophisticated:
function count(what) {
return function(str) {
return str.match(new RegExp(what, 'g')).length;
};
}
// now you can do the this
var countE = count('e');
var resultE = countE('excellent elephants');
var countL = count('l');
var resultL = countL('excellent elephants');
If I understand your comment correctly, you want to do something like this:
function countE(inString) {
var count = 0;
var str = inString ? inString : "eee";
var charLength = str.length;
for (i =0; i <= charLength; i++){
if(str.charAt(i) == "e"){
count++;
}
}
console.log(count);
}
You can also use a regular expression
function countE(str) {
var count = str.match(/e/g).length;
console.log(count);
}
or
function countE(str) {
console.log(str.match(/e/g).length);
}

How to Invert Order of Lines

I have this in a Div (Text actually "wraps" because Div box has short width; except where line breaks are intentional):
"Now is the time
for all good men
to come to the aid
of their country"
"The quick brown fox
jumps over the
lazy dogs"
I would like this:
lazy dogs"
jumps over the
"The quick brown fox"
of their country"
to come to the aid
for all good men
"Now is the time
I've tried using Reverse(); but am not getting the desired results.
Note: I'm not trying to reverse a string per say, but actual lines of text (ie: sentences).
If you got line breaks like this \n, you can do the following:
var lineBreak = "\n",
text = "Now is the time\nfor all good men\nto come to the aid\nof their country";
text = text.split(lineBreak).reverse().join(lineBreak);
If the line break is another sign, change the variable lineBreak.
OK, got it eventually. Based on this answer of mine, I came up with a code that identifies the actual lines inside textarea, even when wrapped.
Next step was to translate div into textarea so we can use the above trick.
Having this, it's simple matter of manipulating the lines using .reverse() method.
Final code is:
$("#btnInvert").click(function() {
var placeholder = $("#MyPlaceholder");
if (!placeholder.length) {
alert("placeholder div doesn't exist");
return false;
}
var oTextarea = $("<textarea></textarea>").attr("class", placeholder.attr("class")).html(placeholder.text());
oTextarea.width(placeholder.width());
//important to assign same font to have same wrapping
oTextarea.css("font-family", placeholder.css("font-family"));
oTextarea.css("font-size", placeholder.css("font-size"));
oTextarea.css("padding", placeholder.css("padding"));
$("body").append(oTextarea);
//make sure we have no vertical scroll:
var rawTextarea = oTextarea[0];
rawTextarea.style.height = (rawTextarea.scrollHeight + 100) + "px";
var lines = GetActualLines(rawTextarea);
var paragraphs = GetParagraphs(lines).reverse();
lines = [];
for (var i = 0; i < paragraphs.length; i++) {
var reversedLines = paragraphs[i].reverse();
for (var j = 0; j < reversedLines.length; j++)
lines.push(reversedLines[j]);
if (i < (paragraphs.length - 1))
lines.push("");
}
rawTextarea.value = lines.join("\n");
placeholder.html(rawTextarea.value.replace(new RegExp("\\n", "g"), "<br />"));
oTextarea.remove();
});
function GetParagraphs(lines) {
var paragraphs = [];
var buffer = [];
$.each(lines, function(index, item) {
var curText = $.trim(item);
if (curText.length === 0) {
if (buffer.length > 0) {
paragraphs.push(buffer);
buffer = [];
}
} else {
buffer.push(curText);
}
});
if (buffer.length > 0)
paragraphs.push(buffer);
return paragraphs;
}
function GetActualLines(oTextarea) {
oTextarea.setAttribute("wrap", "off");
var strRawValue = oTextarea.value;
oTextarea.value = "";
var nEmptyWidth = oTextarea.scrollWidth;
var nLastWrappingIndex = -1;
for (var i = 0; i < strRawValue.length; i++) {
var curChar = strRawValue.charAt(i);
if (curChar == ' ' || curChar == '-' || curChar == '+')
nLastWrappingIndex = i;
oTextarea.value += curChar;
if (oTextarea.scrollWidth > nEmptyWidth) {
var buffer = "";
if (nLastWrappingIndex >= 0) {
for (var j = nLastWrappingIndex + 1; j < i; j++)
buffer += strRawValue.charAt(j);
nLastWrappingIndex = -1;
}
buffer += curChar;
oTextarea.value = oTextarea.value.substr(0, oTextarea.value.length - buffer.length);
oTextarea.value += "\n" + buffer;
}
}
oTextarea.setAttribute("wrap", "");
return oTextarea.value.split("\n");
}
Just put the actual ID of your div and it should work.
Live test case.
warning, this is pseudo code :
lines=[];
index=0;
start=0;
for(characters in alltext){
if(newLine){
lines.push(alltext.substring(start,index);
start=index;
}
i++
}
sortedLines=[]
for(var i=lines.length;i>-1;i--){
sortedLines.push(lines[i]);
html=$('selector').html();
html+=lines[i];
$('selector').append(html);
}
better use split

Categories