Why doesn't .toUpperCase() capitalize str[i]? - javascript

Doing a CoderByte challenge:
Using the JavaScript language, 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.
my solution:
function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyza",
vowels = "aiueo",
newstr = '';
for (var i = 0; i < str.length; i++) {
if (alphabet.indexOf(str[i]) != -1) {
newstr += alphabet[alphabet.indexOf(str[i]) + 1];
} else {
newstr += str[i];
}
}
for (var i = 0; i < vowels.length; i++) {
for (var j = 0; j < newstr.length; j++) {
//toUppercase the vowel in the newstring once found
if (newstr[j] == vowels[i]) {
newstr[j] = newstr[j].toUpperCase();
}
}
}
return newstr;
}
show(LetterChanges("fun times"));
show(LetterChanges("hello*3"));
The toUpperCase() does not capitalize the vowel I want. It seems correct though. I've even tried something like this:
if (newstr[j] == vowels[i]) {
var toCap = newstr[j].toString();
newstr[j] = toCap.toUpperCase();
}
If you think of a better solution, then please answer the toUpperCase() part and then recommend another solution.

Strings in Javascript are primitive types, not objects.
When you set a property in a primitive type (eg, str[i] = 'a'), Javascript creates a new boxed object for that value, mutates it, then throws it away.
For more details, see the spec.
Instead, you should assemble the new string in a mutable array, then call .join('') to convert it to a string.

You can create another string to build the return string, see bellow a fix in your code
function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyza",
vowels = "aiueo",
newstr = '',
returnStr = ''; //added to next step
for (var i = 0; i < str.length; i++) {
if (alphabet.indexOf(str[i]) != -1) {
newstr += alphabet[alphabet.indexOf(str[i]) + 1];
} else {
newstr += str[i];
}
}
for (var i = 0; i < vowels.length; i++) {
for (var j = 0; j < newstr.length; j++) {
//toUppercase the vowel in the newstring once found
if (newstr[j] == vowels[i]) {
returnStr += newstr[j].toUpperCase();
}else{
returnStr += newstr[j];
}
}
}
return returnStr ;
}

You can capitalize the vowels via replace and an uppercasing function:
newstr = newstr.replace(
/[aeiou]/g, // replace all vowels
function(letter) { // called for each match
return letter.toUpperCase();
}
);
Example: http://codepen.io/paulroub/pen/tvhcF

The contents of a string cannot be changed, I.E. they are immutable. Create a new string instead of trying to edit one in-place.

You can make your life easy with the following code
function LetterChanges(str) {
return str.replace(/[a-zA-Z]/g,function(x) {
return String.fromCharCode(x.charCodeAt(0)+1); }).replace(/[aeiou]/g,function(y) {
return y.toUpperCase();
});
}

Related

Double Consonant in JavaScript

I made a function double consonant(). Here it's all well. But when I try to change little the logic with symbol !== in second function double_consonant_2() my program work wrong and i'm confused.
i want to say that each element from sentence which is not equal with vowel. i mean equal with consonant. Double the words and between them add the letter o.
// double consonant with consonant variable.
function double_consonant(sentence) {
var result = "";
var consonant = "qwrtypsdfghjklzxcvbnm";
for (var i = 0; i < sentence.length; i++) {
for (var j = 0; j < consonant.length; j++) {
if (sentence[i] === consonant[j]) {
result += sentence[i] + "o" + sentence[i];
}
}
}
return result;
}
console.log(double_consonant("good"));
// dobule consonant with vowel variable.
function dobule_consonant_2(sentence) {
var result = "";
var vowel = "aeouiAEOUI";
for (var i = 0; i < sentence.length; i++) {
for (var j = 0; j < vowel.length; j++) {
if (sentence[i] !== vowel[j]) {
result += sentence[i] + "o" + sentence[i];
}
}
}
return result;
}
console.log(dobule_consonant_2("here"));
The problem with your second function is that your if filters each vowels independently.
In your example with here, when reaching the e, the second loop will check if the letter is different from a, which is true, and so add the o between, and then continue to check the other vowels.
What you could do is check for all the vowels and then decide :
var isVowel = false;
for (var j = 0; j < vowel.length; j++) {
if (sentence[i] === vowel[j]) {
isVowel = true;
break;
}
}
if(!isVowel) {
result += sentence[i] + "o" + sentence[i];
}
Note that it's not the fastest way, using indexOf in the first method seems easier.

Returning subset using loop

I wrote this code
function sub (str, start, end) {
var newstr = ''
for(var i = 0; i < str.length; i++) {
if(i >= start && i < end) {
newstr += str[i]
}
}
return newstr
}
I expect the output of ('abcd',0,10) to be 'ab', but the actual output is 'a'
If your goal is to get a function which takes starting and ending index to return substring, then you can use slice function on Strings.
var word = 'ascsjdksjdnc';
word.slice(2, 4);
// Output: 'cs'

How a multidimensional array value assignation works in this case?

Why this function does not return an string with the first letter of each word on upper case?
function titleCase(str) {
str = str.split(' ');
for (var i = 0; i < str.length; i++) {
str[i][0] = str[i][0].toUpperCase();
console.log(str);
}
return str;
}
The reason Why this function does not return an string with the first letter of each word on upper case is because strings are immutable.
You cannot change a character within a string.
Therefore this does not work in javascript:
str[i][0] = 'c';
This does not change the string str[i].
However in order to achieve your goal you can make a new string with first letter uppercase and assign it to the variable containing your string.
You need to replace the whole array element with a new string. All you are doing is modifying a string but not what is in the array.
Then you need to join() the array again to get a string returned
function titleCase(str) {
str = str.split(' ');
for (var i = 0; i < str.length; i++) {
str[i] = str[i][0].toUpperCase() + str[i].slice(1);
// ^^ reassign array element with new string ^^
}
return str.join(' ');
}
Ty this:
function titleCase(str) {
str = str.split(' ');
for (var i = 0; i < str.length; i++) {
str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
console.log(str[i], 'i');
}
return str;
}
to explain further:
Get the First letter and convert it to uppercase
str[i].charAt(0).toUpperCase()
This is the rest of the word without the first letter.
str[i].slice(1);
"capitalizeText" method used to covert first character of string to uppercase.
String.prototype.capitalizeText = String.prototype.capitalizeText || function() {
return this.charAt(0).toUpperCase() + this.slice(1);
// return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
}
function titleCase(str) {
str = str.split(' ');
for (var i = 0; i < str.length; i++) {
str[i] = str[i].capitalizeText();
console.log(str[i]);
}
return str.join(" ");
}
$(document).ready(function(){
$('#divResult b').text(titleCase("testing words"));
});
Demo

Writing a string splitting function without using the split method in javascript

I'm trying to create a simple function that takes a string and a delimiter and then splits the string into an array based on the delimiter value. I'm trying to write this function without using the split method in javascript. So say I have a sampleInput = '123$456$789' and a delimiter = '$' then the function stringDelimiter(sampleInput, delimiter) will return ['123', '456', '789'].
var stringDelimiter = function (sampleInput, delimiter) {
var stringArray = [];
var garbageArray = [];
var j = 0;
for (var i = 0; i < sampleInput.length; i++) {
if (sampleInput.charAt(i) == delimiter) {
garbageArray = sampleInput.charAt(i);
j++;
} else {
if (!stringArray[j]) stringArray[j] = '';
stringArray[j] += sampleInput.charAt(i);
}
}
return stringArray;
}
The problem I'm having is if the delimiter appears at the beginning of the string it returns the first element of the array undefined. I'm stuck as to how I can handle this case. So if I have sampleInput = '$123$456$789' and delimiter = '$' it returns ['123', '456', '789'] and not ['undefined','123', '456', '789'].
Any help would be appreciated.
This is a little simpler, and it might do what you want:
var stringDelimiter = function (sampleInput, delimiter) {
var stringArray = [''];
var j = 0;
for (var i = 0; i < sampleInput.length; i++) {
if (sampleInput.charAt(i) == delimiter) {
j++;
stringArray.push('');
} else {
stringArray[j] += sampleInput.charAt(i);
}
}
return stringArray;
}
Your garbageArray seemed unnecessary.
What about using regular expressions?
function x_split(s)
{
return s.match(/([^$]+)/g);
}
E.g.
http://jsfiddle.net/2F9MX/2/
If the current character is delimiter and if the current iteration is 0, continue
This function accepts a string, a delimiter and a flag if empty (aka undefined, null or empty string) elements should be removed from the result array. (Not tested, it was a quick code for now.)
UPDATE
Now it's tested (a bit) and corrected, and I've created a jsFiddle here. Besides, it supports empty delimiter, empty input string, and delimiter with length > 1.
function CustomSplit(str, delimiter, removeEmptyItems) {
if (!delimiter || delimiter.length === 0) return [str];
if (!str || str.length === 0) return [];
var result = [];
var j = 0;
var lastStart = 0;
for (var i=0;i<=str.length;) {
if (i == str.length || str.substr(i,delimiter.length) == delimiter)
{
if (!removeEmptyItems || lastStart != i)
{
result[j++] = str.substr(lastStart, i-lastStart);
}
lastStart = i+delimiter.length;
i += delimiter.length;
} else i++;
}
return result;
}
In case someone needs one for TypeScript (and MicroBit for which I wrote it), here's a altered version of #Scott Sauyet answer for TypeScript:
The code:
function splitString(sampleInput: string, delimiter: string): string[] {
let stringArray = ['']
let j = 0
for (let i = 0; i < sampleInput.length; i++) {
if (sampleInput.charAt(i) == delimiter) {
j++;
stringArray.push('')
} else {
stringArray[j] += sampleInput.charAt(i)
}
}
return stringArray
}
Usage example
let myString = "Lorem ipsum dolor sit amet"
let myArray = splitString(myString, " ")
myArray[0] // "Lorem"
myArray[1] // "ipsum"
You can use this method
const splitCode = (strValue, space) => {
let outPutArray = [];
let temp = '';
for(let i= 0; i< strValue.length; i++){
let temp2 = '';
for(let j= i; j<space.length+i;j++){
temp2 = temp2+strValue[j];
}
if(temp2 === space){
outPutArray.push(temp);
i=i+space.length-1;
temp = '';
}else{
temp = temp+strValue[i];
}
}
return outPutArray.concat(temp)
}

Javascript: Determine if all characters in a string are unique and if not, delete duplicate characters

Have an array set up with a[letter][occurences], but struggling with looping through this array, to check for occurences > 1 and removing the ones that are.
function charFreq(s) {
var i, j;
var a = new Array();
for (j = 0; j < s.length; j++) {
for (i = 0; i < a.length; i++) {
if (a[i][0] == s[j]) {
a[i][1]++;
break;
}
}
if (i == a.length) {
a[i] = [s[j], 1];
}
}
return a[i][0];
}
document.write(charFreq("insert string here"));
This is the mess I've come up with so far:
function check(str) {
var c;
for (c=0; c < a.length; c++) {
if(a[c][1] == 1) {
return true;
break;
} else {
return false;
}
}
}
Using ES6 Set:
// :: unique = Array<any>|string => Array<any>
const unique = xs => [...new Set(xs)]
const dedupe = str => unique(str).join('')
console.log(
unique('foo'), // => ['f', 'o']
dedupe('foo'), // => 'fo'
)
Don't do it that way.
function noDups( s ) {
var chars = {}, rv = '';
for (var i = 0; i < s.length; ++i) {
if (!(s[i] in chars)) {
chars[s[i]] = 1;
rv += s[i];
}
}
return rv;
}
alert(noDups("Shoe fly pie, and apple pan dowdy")); // Shoe flypi,andw
As the length of your string gets longer, your code gets slower by a factor roughly equal to the square of the length of the string.
To delete duplicate characters from an string, you can use the next function that made the user #Cerbrus
function find_unique_characters( string ){
var unique='';
for(var i=0; i<string.length; i++){
if(string.lastIndexOf(string[i]) == string.indexOf(string[i])){
unique += string[i];
}
}
return unique;
}
console.log(find_unique_characters('baraban'));
If you only want to return characters that appear occur once in a
string, check if their last occurrence is at the same position as
their first occurrence.
Your code was returning all characters in the string at least once,
instead of only returning characters that occur no more than once
Link to the thread of stackoverflow Remove duplicate characters from string
​
Here's a quick way:
str = str.split('').filter(function(v,i,self){
return self.indexOf(v) == i;
}).join('');
function RemoveDuplicateLetters(input) {
var result = '', i = 0, char = '';
while (i < input.length) {
char = input.substring(i, i+1);
result += char;
input = input.replace(char,'');
}
return result;
}
I can't see a splice version, so here's one:
function uniqueChars(s) {
var s = s.split('');
var c, chars = {}, i = 0;
while ((c = s[i])) {
c in chars? s.splice(i, 1) : chars[c] = ++i;
}
return s.join('');
}
This assumes only alpha characters, and upper case not equal to lower case.
function uniqueChars(string){
var i= 0, L= string.length, ustring= '', next;
while(i<L){
next= string.charAt(i++);
if(ustring.indexOf(next)== -1) ustring+= next;
}
return ustring.replace(/[^a-zA-Z]/g, '');
}
var s1= 'The quick red fox jumps over the lazy brown dog.';
uniqueChars(s1)
/* returned value: (String)
Thequickrdfoxjmpsvtlazybwng
*/
This returns any unique character-
function uniqueArray(array){
return array.filter(function(itm, i, T){
return T.indexOf(itm)== i;
});
}
var s1= 'The quick red fox jumps over the lazy brown dog.';
uniqueArray(s1.split('')).join('');
/* returned value: (String)
The quickrdfoxjmpsvtlazybwng.
*/

Categories

Resources