How do I push letters to into a string? - javascript

I want to take the var ascii and put it into a string. The code only returns each char within the loop.
function rot13(str) { // LBH QVQ VG!
var newStr = str;
for (var i = 0; i < str.length; i++){
var letter = str.charAt(i);
var code = letter.charCodeAt();
if (code > 77){
ascii = code - 13;
}
else if (code === 32 ){
ascii = code;
}
else{
var ascii = code + 13;
}
}
}
rot13("SERR PBQR PNZC"); //returns FREE CODE CAMP

To answer you, you already have written the code, but just used messed up a bit here and there -
function rot13(str) { // LBH QVQ VG!
console.log (str);
var newStr = str;
var ascii = "";
for (var i = 0; i < newStr.length; i++){
var letter = newStr.charAt(i);
//console.log (letter);
var code = letter.charCodeAt();
//console.log (code);
if (code > 77){
ascii = code - 13;
//console.log (ascii);
}
else if (code === 32 ){
ascii = code;
//console.log (ascii);
}
else{
ascii = code + 13;
//console.log (ascii);
}
var sipher = "";
sipher = String.fromCharCode(ascii);
newStr += sipher;
}
console.log (sipher);
return newStr;
}

Related

Accessing JavaScript var's each char and adding back-slash n to divide string in 2 lines

I am trying to divide my string in 2 lines if string is greater than 15 characters, so i am finding a space after 15 char and putting /n to string so that when var gets printed it should get printed in 2 lines.
following is my JavaScript code. its not working, please if anyone can help.
Thankyou
var name = row.product_name;
var val = 15;
var output;
var flag = false;
console.log(name[0]);
for(i=0; i<row.product_name.length; i++)
{
if(i > val)
{
if(name[i] == ' ')
{
name[i] = "/n";
flag = true;
}
}
if(flag)
{
val = val + 15;
flag = false;
}
}
this can't work because javascript strings are immutable, so you can't reassign name[i]. You have to use replace, slice, split, or other operations on the whole string
var myString = "jsdjposjgiohg squg oiq oih osqdh uh hsquv hup h opsdqh voph";
myStringA=myString.split(" ");
var newString="";
var n=0;
for (var i=0;i<myStringA.length;i++){
n+=myStringA[i].length;
if (n>15){
n=0;
newString+=myStringA[i]+"\n";
}else{
newString+=myStringA[i]+" ";
}
}
console.log(newString);
Strings are immutable in javascript so you need to put the changes in a new variable
Also the newline character is \n not /n
var name = row.product_name;
var val = 15;
var output = "";
var flag = false;
console.log(name[0]);
for(i=0; i<row.product_name.length; i++)
{
output += name[i]
if(i > val)
{
if(name[i] == ' ')
{
output[i] = "\n";
flag = true;
}
}
if(flag)
{
val = val + 15;
flag = false;
}
}

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 !

Longest substring in alphabetical order Javascript

Seeing all the people talking about longest substring in alphabetical order in Python, I have decided to try it in JS.
The function should look for the longest substring inside a given string, where letters are ordered alphabetically.
Here is what I have:
var s = 'azcbobobegghakl'
function substringChecker(s) {
var longestSub = "";
for (var i = 0; i < s.length; i++) {
var count = 0;
var currSub = "";
while((i+count)<=s.length){
var curr = i+count;
var next = curr+1;
var prev = curr-1;
if(curr !== s.length-1) {
if(s[curr] <= s[next]){
currSub += s[curr]
} else {
break;
}
} else {
if(s[curr]>s[prev]) {
currSub += s[curr];
}
}
count++;
}
if(currSub.length >= longestSub.length) {
longestSub = currSub;
}
};
return longestSub;
}
var result = substringChecker(s);;
console.log(result);
The funny thing it works great for all test cases I can come up with, but this one. The result should be "beggh" but it is "begg" instead. Why is the h not showing up, what am I missing?
The algorithm can be linear, I think you are overcomplicating it placing loops inside loops.
I would use something like
function substringChecker(s) {
var longestSub = "",
length = 0,
start = 0,
prev = s[0];
for (var i = 1; i <= s.length; ++i) {
if(i == s.length || s[i] < prev) {
if(length < i-start) {
longestSub = s.substring(start, i);
length = i-start;
}
start = i;
}
prev = s[i];
};
return longestSub;
}
document.write(substringChecker('azcbobobegghakl'));
first I made list of A-z
then check each letter and compare it with the next letter and save it in subString and...
function longest(str) {
//handle the case str is just one letter
if (str.length === 1) return str;
// create a list of alphabet A to Z
const alphabets = [...Array(26)].map(_ => String.fromCharCode(i++), (i = 97));
let longString = "";
let subSting = "";
for (let x = 0; x < str.length; x++) {
let char = str.charAt(x);
const nextChar = str.charAt(x + 1);
let charIndex = alphabets.findIndex(alphabet => alphabet === char);
let nextCharIndex = alphabets.findIndex(alphabet => alphabet === nextChar);
if (nextCharIndex >= charIndex) {
subSting = subSting + nextChar;
} else {
if (!subSting.length) {
subSting = subSting + char;
}
longString = subSting.length > longString.length ? subSting : longString;
subSting = "";
}
}
return longString;
}
console.log(longest("zyba"));

RandomString Error In Output

Is there any way to get this using randomString..
function randomString(length, chars) {
var result = '';
var i;
for (i = 0; i <= 100; i++) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}
var rString = randomString(100, '0');
I need the output like this..
0
00
000
0000
00000
000000
0000000
00000000 and so on till 100
Here is working code.
I renamed the function because it is not a randomString function.
http://jsfiddle.net/8rn5gpze/
function bar(length, chars) {
var result ='', last = '';
for (i = 0; i <= length; i++){
last += chars;
result += last;
result += '<br>';
}
return result;
}
var foo = bar(100, '0');
Try the following script
<script language="javascript">
function randomString(length, chars) {
var result = '';
var i;
var sequencecheck = 1;
var finalresult = '';
for (i = 0; i <= 100; i++)
{
result += chars[Math.round(Math.random() * (chars.length - 1))];
finalresult+=result
if(result.length == sequencecheck)
{
finalresult += "<br/>"
sequencecheck++;
}
}
return finalresult;
}
var rString = randomString(100, '0');
document.write(rString);
</script>
Hope it helps!
If you want a simple output to the console just use this:
function randomString(length, chars) {
var result = '';
for (i = 1; i <= length; i++) {
result += chars;
console.log(result);
}
}
To get your output you could use this function: demo
HTML
<div></div>
For demonstration purposes.
JavaScript
function strTimes(str,times){
var fullStr = "";
for( var i = 0 ; i < times ; i ++ )
fullStr += str;
return fullStr;
}
function outputZeroes(levels,outputToElement){
var newLine = ( outputToElement ) ? "<br>" : "\n";
var str = "";
for( var i = 1 ; i < levels ; i ++ ){
str += strTimes("0",i);
str += newLine;
}
return str;
}
var div = document.querySelector("div");
div.innerHTML = outputZeroes(10,true);
The outputZeroes() function accepts to parameters, the first one is the amount of levels you want, and the second one is a boolean that decides which new line should be used, if set to true, it will be <br> for outputting to html elements, and if false it will be \n for outputting to anything else, by default is false.
Hope it helps!

JavaScript Decrementing Alphabet Function

New to the JavaScript language and need help creating a function which generates the following display.
abcdefghijklmnopqrstuvwxyz
bcdefghijklmnopqrstuvwxyz
cdefghijklmnopqrstuvwxyz
defghijklmnopqrstuvwxyz
.... and so on, all the way down to
xyz
yz
z
I am not asking for handouts, just a little kickstart for a beginner to get started! Links, hints, tips, anything helps! Thanks!
Arrays and loops are powerful when combined.
var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
console.log(alphabet.join(''));
while (alphabet.​length > 0) {
alphabet.shift();
console.log(alphabet.join(''));
}​​​
Edit:
If you really need your decremented alphabet to be left-padded, you can use this:
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var letters = alphabet.split('');
var addPadding = (function (minLength) {
return function (shortString) {
if (shortString.length < minLength) {
return new Array(
minLength - shortString.length + 1
).join(' ') + shortString;
}
};
}(alphabet.length));
console.log(alphabet);
while (letters.length > 0) {
letters.shift();
console.log(addPadding(letters.join('')));
}
Edit:
Here is a much simpler answer:
function decrementingAlphabet () {
var alphabet = 'abcdefghijklmnopqrstuvwxyz';
function iterate(spaces, letters) {
if (letters.length > 0) {
console.log(spaces + letters);
iterate(spaces + ' ', letters.substring(1));
} else {
return;
}
}
iterate('', alphabet);
}
This is simple example.
var str = '';
for (var s=0; s < 26; ++s) {
str = '';
for (var i=0; i < 26 - s; ++i) {
str += String.fromCharCode(97+s+i);
}
document.write(str + "<br/>");
}
​
See http://jsfiddle.net/G5Gds
Hmm, maybe this will help put you on the right track?
var str = '';
// Find out what 'a' is in ASCII
var baseLetterCode = 'a'.charCodeAt(0);
// Loop once for each letter
for (var i = 0; i < 26; ++i) {
// Append to string
str += String.fromCharCode(baseLetterCode + i);
}
In character codes, small alphabets lie from 97 onwards(97 for a). You need to use 2 for loops to print such series.
Here is your jsfiddle demo:
var display='';
for(var i=97;i<123;i++){
var s='';
for(var j=i;j<123;j++){
s+= String.fromCharCode( j );
}
display+=s;
}
alert(display);
(function() {
var theENalphabet = [];
for (var charNow = "a".charCodeAt(0); charNow <= "z".charCodeAt(0); charNow += 1) {
theENalphabet.push(String.fromCharCode(charNow));
}
var isNow = 0;
function decrAlph(startAt) {
var alphString = "";
for (var i = startAt; i < theENalphabet.length; i += 1) {
alphString += theENalphabet[i];
}
console.log(alphString);
isNow++;
while (isNow < theENalphabet.length) {
decrAlph(startAt + 1);
}
};
decrAlph(0);
})();
The charCode getting could be abstracted into a function:
var getCharCode = function(el){
return String.prototype.charCodeAt.call(el, 0);
};
getCharCode("a"); // returns 97..

Categories