Javascript For Loop: Assignment to character not working - javascript

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;
}

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"));

how to decode string in 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

Simple Quiz Game JavaScript

I'm just learning now. Can you please help me, why am I not getting the correct output. This is my code:
//ask questions
var quiz = [
["When is Bulgaria established?", 681],
["What year was it before 16 years?", 2000],
["When does WWII ends?", 1945]
];
//variables
var answer = [];
var correct = [];
var wrong = [];
var correctAns = 0;
var wrongAns = 0;
var oList = "<ol>";
//function to print the result in ordered list
function printResult(result){
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[i] + "</li>";
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML = message;
}
//looping, adding correct and wrong answeres
for(var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if(parseInt(answer[i]) == quiz[i][1]){
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if(correct.length < 1 || correct == undefined){
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1){
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if(wrongAns > 0){
print(printResult(wrong));
}
}
I have watched this code over and over again and I still can't understand why am I getting undefined as a result. In the debugger, after the loop I check my vars and everything seems ok.
In your printResult function you are using var i instead of j,
Also you better use innerHtml+=message;
//ask questions
var quiz = [
["When is Bulgaria established?", 681],
["What year was it before 16 years?", 2000],
["When does WWII ends?", 1945]
];
//variables
var answer = [];
var correct = [];
var wrong = [];
var correctAns = 0;
var wrongAns = 0;
//function to print the result in ordered list
function printResult(result){
//HERE:
var oList = "<ol>";
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[j] + "</li>";
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML += message;
}
//looping, adding correct and wrong answeres
for(var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if(parseInt(answer[i]) == quiz[i][1]){
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if(correct.length < 1 || correct == undefined){
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1){
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if(wrongAns > 0){
print(printResult(wrong));
}
}
<div id="output">
</div>
Basically you have three problems.
reuse of oList, the variable should be inside declared and used only in printResult.
Inside of printResult, use of i where j have been used and
At print, you replace the actual content with new content.
Just a small hint with variable names for counting. It is good practise to start always with i instead of j and go on with the letters in the alphabet.
var quiz = [["When is Bulgaria established?", 681], ["What year was it before 16 years?", 2000], ["When does WWII ends?", 1945]],
answer = [],
correct = [],
wrong = [],
correctAns = 0,
wrongAns = 0;
//function to print the result in ordered list
function printResult(result) {
var oList = "<ol>"; // !!! move variable inside of the function
for (var j = 0; j < result.length; j++) {
oList += "<li>" + result[j] + "</li>"; // !!! use j indstead if i
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML += message; // !!! append message
}
//looping, adding correct and wrong answeres
for (var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if (parseInt(answer[i]) == quiz[i][1]) {
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if (correct.length < 1 || correct == undefined) {
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1) {
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if (wrongAns > 0) {
print(printResult(wrong));
}
}
Your main mistake is using i intead of j:
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[j] + "</li>";// here was i before
}

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);
}

JavaScript - how to change elements of a string?

JS newbie here. I want to write a basic program that changes each element in a string based on a condition. If the letter is uppercase we swap it to lowercase, if the letter is already lowercase we swap it to uppercase. Why is this not working? Thanks!
function SwapCase(str){
for (var i = 0; i < str.length; i++) {
if (str.charAt(i)===str.charAt(i).toUpperCase()) {
str.charAt(i).toLowerCase();
} else{}
str.charAt(i).toUpperCase();
}
return str;
}
SwapCase("gEORGE");
Currently you do not write back your changes. You could, for example, do something like this:
function SwapCase(str){
var result = '';
for (var i = 0; i < str.length; i++) {
if (str.charAt(i)===str.charAt(i).toUpperCase()) {
result += str.charAt(i).toLowerCase();
} else{
result += str.charAt(i).toUpperCase();
}
}
return result;
}
function SwapCase(str){
var sReturn = "";
for (var i = 0; i < str.length; i++) {
if (str.charAt(i)===str.charAt(i).toUpperCase()) {
sReturn += str.charAt(i).toLowerCase();
} else{
sReturn += str.charAt(i).toUpperCase();
}
}
return sReturn;
}
Doing the same thing with String Prototyping and some shorthand notation.
String.prototype.swapCase = function(){
var returnString = '';
for (var i = 0; i < this.length; i++) {
returnString += (this[i]===this[i].toUpperCase())
? this[i].toLowerCase()
: this[i].toUpperCase();
}
return returnString;
};
console.log("Hallo".swapCase());

Categories