Javascript- Uppercase letters to lower case and vise versa - javascript

I am interested in making any uppercase letters lowercase and any lowercase letters uppercase.
If I have code like the below code, what should I put in the blank spaces of this if/else statement: if (string[i] == ) and the else if (string [i] == ). Here is the rest of my code:
var sentence = "Whats Up! MAKE ME uppercase or LOWERCASE";
var theString = sentence.split("")
for (var i = theString.length; i >= 0; i--) {
if (theString[i] == ) {
theString[i].toLowerCase();
}
else if (theString [i] == ) {
theString[i].toUpperCase();
}
}
var connectedSentence = theString.join("");
console.log(connectedSentence);
Have I made any other mistakes? The expected output is make me UPPERCASE OR lowercase.

You can use split, map and join to work fast on strings in javascript.
var sentence = "Whats Up! MAKE ME uppercase or LOWERCASE"
var inversed = sentence.split('').map(function(c) {
return c.toLowerCase() == c ? c.toUpperCase() : c.toLowerCase();
}).join('');

if (theString[i] == theString[i].toUpperCase()) {
theString[i]= theString[i].toLowerCase();
}
else if (theString[i] == theString[i].toLowerCase()) {
theString[i]= theString[i].toUpperCase();
}

You could simply test with RegExp;
var flipCase = function(str) {
var arr = str.split('');
var c, rgx = /[a-z]/;
str = '';
while (arr.length) {
c = arr.shift();
str += rgx.test(c) ? c.toUpperCase() : c.toLowerCase();
}
return str;
};
alert(flipCase("Hello World !"));

Related

how to filter the elements based on data type in given list

filterString('str$$$1232text%<>');
The answer should be like
a = 'strtext'
b = '$$$%<>'enter code here
c = '1231'
Going by your question, assuming it to be in string, two possible ways are checking by regex or Unicode.
word = 'str$$$1232text%<>'
console.log(filterStringByUnicode(word))
console.log(filterStringByRegex(word))
function filterStringByRegex(word){
let str = num = spl = '';
[...word].forEach(el => {
if(el.match(/[a-z]/))
str += el;
else if(el.match(/[0-9]/))
num += el;
else
spl += el;
})
return {a:str,b:spl,c:num}
}
function filterStringByUnicode(word){
let str = num = spl = '';
[...word].forEach(el => {
let unicode = el.charCodeAt(0)
if(unicode >= 91 && unicode <= 122) //Unicode for a-z
str += el;
else if(unicode >= 48 && unicode <= 57) //Unicode for numbers
num += el;
else //rest
spl += el;
})
return {a:str,b:spl,c:num}
}
Your question seems not to be about filters but about how to split a string into substrings following some rules. I suggest you to look around RegExp(theRule) in JS.
A solution could be similar to :
var aString = 'str$$$1232text%<>';
var a=''; var b=''; var c='';
var regexA = new RegExp('[a-z]'); // lowercase a to z
var regexB = new RegExp('$%<>'); // only this special chars but you can add more
var regexC = new RegExp('[0-9]'); // 0 to 9
for(const aCharacter of aString.split('')){ // split will make an Array of chars
if (regexA.test(aCharacter) // the 'test' method return true if the char respect the regex rule
a = a.concat(aCharacter);
if (regexB.test(aCharacter)
b = b.concat(aCharacter);
if (regexC.test(aCharacter)
c = c.concat(aCharacter);
}

Is there a way to match every letter in a string and insert a specific letter in their place?

For example if I had the string "GCG", I'd like to insert a
"C" at every "G" match, and a "G" at every "C" match, making it GCCGGC.
So far I have the following, but it prints GCGCGC.
function pairElement(str) {
for(i = 0; i < str.length; i++) {
if(str[i] == "G") {
return str.replace(/([GC+/])/g, "GC");
} else if (str[i] == "C") {
return str.replace(/([?=CG+/])/g, "CG");
}
}
}
pairElement("GCG");
Edit: I think only the first if statement is executing and not running the else if. Are there any other methods I can use to search for different letters, not only one, and insert another letter depending on what the search for letter is?
You can convert the string into array using splitand then iterate through the array and replace each character.
Then you can use join to convert the array into string.
var string = 'GCG';
var str = string.split('').map(c => {
if(c === 'G') c = 'GC';
else if (c === 'C') c = 'CG';
return c;
}).join('');
console.log('String ' + string);
console.log('New String ' + str);
you can do
function pairElement(str) {
return str.replace(/G|C/g, e => e=='G'?'GC':'CG')
}
console.log(pairElement("GCG"));
You are not using recursion. Once it hits the return statement, the control exits. A better way would be to use regex as one of the answers suggested but if you want to just make tiny modifications in your own code, maybe try something like this.
function pairElement(str) {
var newStr= ""; // using new string to make it more readible
for(i = 0; i < str.length; i++) {
if(str[i] == "G") {
newStr = newStr + str[i] + "C";
} else if (str[i] == "C") {
newStr = newStr + str[i] + "G";
} else {
newStr = newStr + str[i]; //you didn't specify what do you want to do in this case
}
}
return newStr;
}
pairElement("GCG");

CoderByte Letter Changes Java Script

The question is :
Using the JavaScript, have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.
function LetterChanges(str){
var result = "";
for(var i = 0; i < str.length; i++) {
var letters = str[i];
if (letters == "a"|| letters == "e"|| letters == "i"|| letters == "o"|| letters =="u") {
letters = letters.toUpperCase();
result+=letters;
} else if (letters == "z") {
letters = "a";
} else {
var answer = "";
var realanswer="";
for (var i =0;i<str.length;i++) {
answer += (String.fromCharCode(str.charCodeAt(i)+1));
}
realanswer += answer
}
}
return realanswer;
return result;
}
LetterChanges();
basically, if return realanswer is placed before return result and LetterChanges is called with "o" i get the output undefined. But if it is called with a non vowel such as "b" it will output "c" which is correct.
now if i place return result before return realanswer it will work properly for vowels but not for other letters. thanks for the help
function LetterChanges(str) {
return str
.replace(/[a-zA-Z]/g, (x) => String.fromCharCode(x.charCodeAt(0)+1))
.replace(/[aeiou]/g, (v) => v.toUpperCase());
}
The first part modifies the consonants by an increment of 1.
Regex is isolating the characters with [] versus no brackets at all. g ensures that the regex is applied anywhere in the string, as opposed to not putting g which gives you the first occurrence of the search.
You have to convert the characters in the string to their Unicode because incrementing is a math operation. x.charCodeAt(0) is saying at the index of 0 of the string in the argument. The increment of 1 is not within the parentheses but outside.
The second part modifies the vowels to upper case.
This is pretty straightforward, the regex only finds the individual characters because [] are used, g for anywhere in the string. and the modifier is to make the characters become upper case.
function LetterChanges(str) {
var lstr = "";// Took a variable to store after changing alphabet//
for(var i=0;i<str.length;i++){
var asVal = (str.charCodeAt(i)+1);// To convert string to Ascii value and 1 to it//
lstr += (String.fromCharCode(asVal));// To convert back to string from Asii value//
}
console.log("Before converting vowels :"+lstr); //Printing in console changed alphabet//
var neword =""; // variable to store word after changing vowels to uppercase//
for(i=0;i<lstr.length;i++){
var strng = lstr[i]; // Storing every letter in strng variable while running loop //
if(strng=="a"||strng=="e"||strng=="i"||strng=="o"||strng=="u"){
neword += strng.toUpperCase(); // If it a vowel it gets uppercased and added //
}
else{
neword += strng; // If not vowel , it just gets added without Uppercase //
}
}
console.log("After converting vowels :"+neword); //Printing in console the word after captilising the vowels //
}
LetterChanges("Goutham"); // Calling a function with string Goutham //
function letterChanges(str) {
let res = '';
let arr = str.toLowerCase().split('');
// Iterate through loop
for(let i = 0; i < str.length; i++) {
// Convert String into ASCII value and add 1
let temp = str.charCodeAt(i) + 1;
// Convert ASCII value back into String to the result
res += (String.fromCharCode(temp));
}
console.log(res);
// Replace only vowel characters to Uppercase using callback in the replace function
return res.replace(/[aeiou]/g, (letters) {
return letters.toUpperCase();
});
}
function LetterChanges(str) {
return str
.split('')
.map((c) => String.fromCharCode((c >= 'a' && c <= 'z') ? (c.charCodeAt(0)-97+1)%26+97 : (c >= 'A' && c <= 'Z') ? (c.charCodeAt(0)+1-65)%26+65 : c.charCodeAt(0)))
.join('').replace(/[aeiou]/g, (letters) => letters.toUpperCase());
}
export const letterChange=(str)=>{
let newStr = str.toLowerCase().replace(/[a-z]/gi, (char)=>{
if(char==="z"){
return "a"
}else{
return String.fromCharCode(char.charCodeAt()+1)
}
})
let wordCap = newStr.replace(/a|e|i|o|u/gi, char => char.toUpperCase())
return wordCap
}
function changeLetters(str) {
var result = "";
for (var i = 0; i < str.length; i++) {
var item = str[i];
if (
item == "a" ||
item == "e" ||
item == "i" ||
item == "o" ||
item == "u"
) {
item = item.toUpperCase();
result += item;
} else if (item == "z") {
letters = "a";
result += item;
} else {
result += String.fromCharCode(str.charCodeAt(i) + 1);
}
}
return result;
}

Debugging JavaScript for Palindrome Function

function palindrome(str) {
str = str.replace(' ', '');
str = str.replace(',', '');
str = str.replace('.', '');
str = str.toLowerCase();
if (str.length % 2 === 0) {
var x = 0;
while (x < (str.length - x)) {
if (str.charAt(x) === str.charAt((str.length - x) - 1)) {
x++;
} else {
return false;
}
}
return true;
} else {
var y = 0;
while (y < (str.length - y - 1)) {
if (str.charAt(y) === str.charAt((str.length - y) - 1)) {
y++;
} else {
return false;
}
}
return true;
}
}
palindrome("eye");
This may not be the most effecient way of solving this, but I begin by remove extraneous characters, then I used an if/else to split out even and odd string lengths. Within each, I only check equality of characters up through the middle of the word - since past that would be repetitious.
However, after multiple changes and looking into other solutions for the problem, I still cannot get mine to pass for a particular case: palindrome("never odd or even")
If it helps, it passes for "race car" and "almostomla" and "eye".
Thanks in advance!
The problem is that the native replace Javascript function is only replacing a single occurrence in the string. Use Regex to account for all of the matches within the string.
However, keep in mind that the "." character is used in Regex as a wildcard so you need to escape it with a backslash to tell Regex you're specifically looking for the "." character. See this JSFiddle as an example: https://jsfiddle.net/on333yf9/3/
function palindrome(str) {
str = str.replace(/ /g, '');
str = str.replace(/,/g, '');
str = str.replace(/\./g, '');
str = str.toLowerCase();
if (str.length % 2 === 0) {
var x = 0;
while (x < (str.length - x)) {
if (str.charAt(x) === str.charAt((str.length - x) - 1)) {
x++;
} else {
return false;
}
}
return true;
} else {
var y = 0;
while (y < (str.length - y - 1)) {
if (str.charAt(y) === str.charAt((str.length - y) - 1)) {
y++;
} else {
return false;
}
}
return true;
}
}
The problem is because of the following lines:
str = str.replace(' ', '');
str = str.replace(',', '');
str = str.replace('.', '');
It does replace all white spaces, commas or dots globally, it just replaces one space, comma and dot, if it's there. You have to find all spaces, commas and dots and remove them. This is what you can do,
str = str.replace(/ /g, '');
str = str.replace(/,/g, '');
str = str.replace(/./g, '');
The g character means to repeat the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
Edited:
You can do something like this:
if(str.replace(/ /g, '').length != 0){
str = str.replace(/ /g, '');
}
if(str.replace(/,/g, '').length != 0){
str = str.replace(/,/g, '');
}
if(str.replace(/\./g, '').length != 0){
str = str.replace(/\./g, '');
}
Unless you want to write your own code why not user reverse/join?
function palindrome(str)
{
str = str.split(' ').join('');
str = str.split(',').join('');
str = str.split('.').join('');
str = str.toLowerCase();
if (str.split('').reverse().join('') == str)
{
return true;
}
else
{
return false;
}
}
palindrome("never odd or even");

Is there a way I can change the contents of a variable in Camel Case to space separated words?

I have a variable which contains this:
var a = "hotelRoomNumber";
Is there a way I can create a new variable from this that contains: "Hotel Room Number" ? I need to do a split on the uppercase character but I've not seen this done anywhere before.
Well, you could use a regex, but it's simpler just to build a new string:
var a = "hotelRoomNumber";
var b = '';
if (a.length > 0) {
b += a[0].toUpperCase();
for (var i = 1; i != a.length; ++i) {
b += a[i] === a[i].toUpperCase() ? ' ' + a[i] : a[i];
}
}
// Now b === "Hotel Room Number"
var str = "mySampleString";
str = str.replace(/([A-Z])/g, ' $1').replace(/^./, function(str){ return str.toUpperCase(); });
http://jsfiddle.net/PrashantJ/zX8RL/1/
I have made a function here:
http://jsfiddle.net/wZf6Z/2/
function camelToSpaceSeperated(string)
{
var char, i, spaceSeperated = '';
// iterate through each char
for (i = 0; i < string.length; i++) {
char = string.charAt(i); // current char
if (i > 0 && char === char.toUpperCase()) { // if is uppercase
spaceSeperated += ' ' + char;
} else {
spaceSeperated += char;
}
}
// Make the first char uppercase
spaceSeperated = spaceSeperated.charAt(0).toUpperCase() + spaceSeperated.substr(1);
return spaceSeperated;
}
The general idea is to iterate through each char in the string, check if the current char is already uppercased, if so then prepend a space to it.

Categories

Resources