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());
Related
I wrote this code but it seems to keep printing out seal onto the console? Is there another ways to print the correct answer using arrays?
//i.stack.imgur.com/i8D8q.png
var items = "a=65/b=923/c=76/d=896/e=1/f=64/g=945/h=203/i=66";
function proto (thisone, order) {
proto[order] = thisone;
}
function proto2(thisone) {
proto2[thisone.split("=")[0]] = thisone.split("=")[1];
}
function animalMax (value, order2) {
if (!proto2[value.split("=")[0]]) {
proto(value, order2);
} else {
proto("null=-1", order2);
}
for (var y = 0; y < sp.length; y++) {
if (sp[y].split("=")[1] > Number(proto[order2].split("=")[1]) && !proto2[sp[y].split("=")[0]]) {
proto(sp[y], order2);
}
}
}
var sp = items.split("/");
for (var i = 0; i < sp.length; i++) {
animalMax(sp[i], i);
proto2(proto[i]);
}
var final = "";
for (var p = 0; p < sp.length; p++) {
final += proto[p];
}
console.log(final);
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"));
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
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;
}
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);
}