Swapcase Javascript - javascript

I am definitely stuck on this one and could use your help. What do you think?
var swapcase = function(str) {
var string = str.split("");
for (var i = 0; i < string.length; i++) {
if (str.charAt(i) <= 'a' && str.charAt(i) >= 'z') {
str.charAt(i).toUppercase();
} else if (str.charAt(i) <= 'A' && str.charAt(i) >= 'Z') {
str.charAt(i).toLowercase();
}
}
str = letters.join("");
console.log(str);
var text = "Life is 10% what happens to you, and 90% of how you REACT to it";
swapCase(text);
};

Your code has a few errors:
JavaScript is case-sensitive: is the function called swapcase or swapCase?
string isn't a great variable name, especially because you refer to it by a different name (letters) at the end of the function.
Your comparison operators are inverted. Try >= 'a', <= 'z', etc.
JavaScript is case-sensitive: you should be calling toUpperCase and toLowerCase.
You're never calling swapCase aside from inside the function itself.
The fixed version:
var swapCase = function(str) {
var letters = str.split("");
for (var i = 0; i < letters.length; i++) {
if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
letters[i] = str.charAt(i).toUpperCase();
} else if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
letters[i] = str.charAt(i).toLowerCase();
}
}
str = letters.join("");
console.log(str);
return str;
};
var text = "Life is 10% what happens to you, and 90% of how you REACT to it";
swapCase(text);
An easier way to test the case of a character would be:
if (str.charAt(i).toLowerCase() === str.charAt(i)) {
// Character is lower case or not a letter
} else {
// Character is upper case
}

Related

How to convert string with mix of upper and lower case randomly

I would like to convert the string with a mix of upper and lower case. For example, if I have string Mark, I need an output as mARk, or Lewis to convert as lEwIs. How can I achieve this in vanilla JavaScript?
Note: The rule of conversion is random.
I've tried Camelize function, but that not giving me an expected output:
function camelize(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(letter, index) {
return index === 0 ? letter.toLowerCase() : letter.toUpperCase();
}).replace(/\s+/g, '');
}
This will do the trick. Edited to make random
function flipCase(str) {
var flip = '';
for (var i = 0; i < str.length; i++) {
if(Math.random() > .5){
flip += str.charAt(i).toUpperCase();
} else {
flip += str.charAt(i).toLowerCase();
}
}
return flip;
}
I know you mentioned in comments that you wanted it to be random, but for other readers who are looking for a function to invert the casing, here is one way of doing it:
function camelize(str) {
var inverted = "";
for (var i = 0; i < str.length; i++) {
if (str.charCodeAt(i) >= 65 && str.charCodeAt(i) <= 90)
inverted += str.charAt(i).toLowerCase();
else
inverted += str.charAt(i).toUpperCase();
}
return inverted;
}
console.log(camelize("Mark"));
console.log(camelize("Lwies"));
And here is another way using Array.map():
function camelize(str) {
return Array.from(str).map(l => (l.charCodeAt(0) >= 65 && l.charCodeAt(0) <= 90) ? l.toLowerCase() : l.toUpperCase()).join('');
}
console.log(camelize("Mark"));
console.log(camelize("Lwies"));

How to determine if a character is alphanumeric using comparison operator?

I'm taking freecodecamp challenge "Check for Palindromes". Write a function to check if a given string is palindrome. Here is my code:
function palindrome(str) {
str = str.toLowerCase();
for(var i=0; i<str.length; i++){
if((str[i] > 'z' || str[i] < 'a') && (str[i] < '0' || str[i] > '9')){
str = str.replace(str[i], '');
}
}
for(i=0; i<str.length/2; i++){
if(str[i] != str[str.length-1-i]){
return false;
}
}
return true;
}
But it not worked properly. When I use replace(/[\W_]/g, ''); :
function palindrome(str) {
str = str.toLowerCase().replace(/[\W_]/g, '');
// for(var i=0; i<str.length; i++){
// if((str[i] > 'z' || str[i] < 'a') && (str[i] < '0' || str[i] > '9')){
// str = str.replace(str[i], '');
// }
// }
for(i=0; i<str.length/2; i++){
if(str[i] != str[str.length-1-i]){
return false;
}
}
return true;
}
The function worked properly. Is my first method not correct?
Palindromes ignore capitalization, spaces, punctuation and newlines and so on.
So:
A man. A plan. A canal: Panama!
Is a valid palindrome.
As such, you need to strip all punctuation and whitespace out of your string before trying to evaluate it, such that the string you're actually evaluating is:
amanaplanacanalpanama
Then it's easy to do whatever comparator you'd like on the remaining characters.
I did one of these a while ago and included some tests, it might be worth looking at: https://github.com/pvencill/palindrome

Missing Letter Function - Why is it returning undefined?

I'm doing one of the bonfires on Free Code Camp and I'm close to the end, but there's one last bit I can't figure out!
The function should take a string and return what letter is missing (based on the alphabet a-z). It works fine except when the letter that's missing is 'i', where it returns undefined.
I put an additional if statement in to check that when the missing letter is 'i', it meets the criteria of the other if statement (and therefore should execute those lines of code) and it matched, so I've no idea why it would return undefined.
function fearNotLetter(str) {
missingLetter = '';
charCode = 0;
for (i = 0; i < str.length -1 ; i++) {
charCode = str.charCodeAt(i);
if (str.charCodeAt(i + 1)-charCode == 2) {
missingLetter = str.charCodeAt(i)+1;
missingLetter = String.fromCharCode(missingLetter);
} else {
missingLetter = undefined;
}
}
console.log(missingLetter);
return missingLetter;
}
fearNotLetter("abcdefghjklmno");
Really appreciate any help anyone can give.
Thanks in advance.
Because you are setting the value in every round without a missing letter to undefined - even if you found one in the loop before.
I suggest to declare all variable before use with var keyword and initialize missingLetter with undefined.
Then you can break the loop if the missing letter is found.
function fearNotLetter(str) {
var missingLetter = undefined,
charCode,
i;
for (i = 0; i < str.length - 1 ; i++) {
charCode = str.charCodeAt(i);
if (str.charCodeAt(i + 1) - charCode == 2) {
missingLetter = String.fromCharCode(charCode + 1);
break;
}
}
return missingLetter;
}
console.log(fearNotLetter("abcdefghjklmno"));
Try this, you are missing to break the loop once you get the missing letter and in the next iteration missing letter is set to undefined.
function fearNotLetter(str) {
missingLetter = '';
charCode = 0;
for (i = 0; i < str.length -1 ; i++)
{
charCode = str.charCodeAt(i);
if (str.charCodeAt(i + 1)-charCode == 2) {
missingLetter = str.charCodeAt(i)+1;
missingLetter = String.fromCharCode(missingLetter);
break;
}
else
{
missingLetter = undefined;
}
}
console.log(missingLetter);
return missingLetter;
}
fearNotLetter("abcdefghjklmno");

trying to convert a letter to uppercase using .toUpperCase()... doesn't work?

I'm trying to convert a character in an array to uppercase using .toUpperCase(), but it doesn't work. I'm pretty sure my logic is correct, so not sure why it's not working?
var test = "hello*3";
function LetterChanges(str) {
//var testArr = str.split("");
var tempArr = [];
for (i = 0; i < str.length; i++) {
if (str.charCodeAt(i) >= 97 && str.charCodeAt(i) <= 122) {
tempArr.push(str.charCodeAt(i));
tempArr[i] = tempArr[i] + 1;
tempArr[i] = String.fromCharCode(tempArr[i]);
if (tempArr[i] == "p" || tempArr[i] == "i") {
tempArr[i].toUpperCase();
console.log(tempArr[i]); //this will display "i" and "p".. why?
}
} else {
tempArr[i] = str[i];
}
}
console.log(tempArr); //this display [ 'i', 'f', 'm', 'm', 'p', '*', '3' ]
str = tempArr.join("");
return str;
}
So it seems that when I'm comparing "p" and "i" it was able to detect it, but it doesn't convert it to uppercase.
Any help would be appreciated. Thanks!
console.log(tempArr[i]); //this will display "i" and "p".. why?
because you were not storing the converted value back to the variable
make it
tempArr[i] = tempArr[i].toUpperCase();
The above answer is correct, however I slightly modified the code you wrote,
as things can be achieved without using arrays.
var test = "hello*3";
LetterChanges(test)
function LetterChanges(str) {
var newStr = ""
for (i = 0; i < str.length; i++) {
var ch = str[i];
if(ch >='A' && ch<='z'){
ch = String.fromCharCode(ch.charCodeAt(0) + 1);
if(ch == 'p' || ch == 'i')
ch = ch.toUpperCase();
}
newStr += ch;
}
console.log(newStr);
return newStr;
}
Here is the fiddle : https://jsfiddle.net/fzme18q0/2/

Best way to check if a character is a number of letter in javascript?

In javascript whats the best way to check if a character (length 1), is a number (i.e. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9) or a letter (i.e. A to Z, a to z)?
Thanks
Why not:
function isNumber(i) {
return (i >= '0' && i <= '9');
}
function isLetter(i) {
return ((i >= 'a' && i <= 'z') || (i >= 'A' && i <= 'Z'));
}
I wrote a little test case for you, at least for the numeric checking function.
Considering the fact that all functions returns true with either a numberic 1 or a string '1' literal, using an Array seems to be the fastest way (at least in Chrome).
var isNumericChar = (function () {
var arr = Array.apply(null, Array(10)).map(function () { return true; });
return function (char) { return !!arr[char]; };
})();
However, if you accept that it might return false for 1, the switch statement is then significantly faster.
Try this.
function validate_string() {
var str = "a"; //change to desired value;
var regX = new RegExp("([0-9A-Za-z])");
var ans = false;
if(str.length == 1) {
ans = regX.test(str);
}
return ans;
}
Edit: Refactored my answer.
function validateString(char) {
let regx = new RegExp(/^[0-9A-Za-z]{1}$/g);
return regx.test(char);
}
validateString('4'); // true
validateString('as'); // false
validateString(''); // false
validateString(); // false
Maybe try something like this
var sum = 0; //some value
let num = parseInt(val); //or just Number.parseInt
if(!isNaN(num)) {
sum += num;
}
This blogpost sheds some more light on this check if a string is numeric in Javascript | Typescript & ES6
You can check for the type of the variable
function checkType(input){
console.log(typeof input)
}
checkType(1234); //number
checkType('Hello') //string
Here is an updated version
function checkType(i){
var input = i.toString(); //convert everything to strings to run .lenght() on it
for(var i=0; i<input.length; ++i){
if(input[i] >= '0' && input[i] <= '9'){
console.log(input[i]+' is a number');
}else if((input[i] >= 'a' && input[i] <= 'z') || (input[i] >= 'A' && input[i] <= 'Z')){
console.log(input[i]+' is a letter');
}
}
}
checkType('aa9fgg5')

Categories

Resources