Home > database >  Why doesn't this function change the case of the string when it has a similar character like th
Why doesn't this function change the case of the string when it has a similar character like th

Time:06-29

Can't understand why the following function works for some strings an didn't work for some which has a similar character like the first.

const change = (str,y) => (str.toLowerCase().replace(str[y],str[y].toUpperCase()));

console.log(change('London',3)); //lonDon
console.log(change('Lagos',3)); //lagOs
console.log(change('Germany',3)); //gerMany
console.log(change('Dcoder',3)); //Dcoder 
console.log(change('Bobby',3)); //Bobby

CodePudding user response:

The function String.prototype.replace replaces the first occurrence when the first argument is a string.

You can split the string change the index to uppercase and finally join the chars.

const change = (str, y) => {
  const lowercase = str.toLowerCase().split("");
  lowercase[y] = str[y].toUpperCase();
  return lowercase.join("");
};

console.log(change('London',3));
console.log(change('Lagos',3));
console.log(change('Germany',3));
console.log(change('Dcoder',3));
console.log(change('Bobby',3));

CodePudding user response:

str[3] in "Dcoder" is 'd' and in replace the first charecter is 'D' , so than replaced you should change code to this:

const change = (str,y) => {
str = str.toLowerCase()           
str=str.slice(0,y) str[y].toUpperCase() str.slice(y 1)    
return str}

CodePudding user response:

Or, in a slightly shortened manner:

const change = (str, n) =>
  str.split("")
     .map((c,i)=>i==n?c.toUpperCase():c.toLowerCase())
     .join("");

['London','Lagos','Germany','Dcoder','Bobby'].forEach(w=>console.log(change(w,3)));

CodePudding user response:

I'm not sure why your function isn't working as expected, but one possible workaround would be to use the built-in string method upper:

def change_case(s):
    return s.upper()
  • Related