Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
Why doesn't this function change the case of the string when it has a similar character like the first letter?

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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));

about 4 years ago · Juan Pablo Isaza Report

0

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}
about 4 years ago · Juan Pablo Isaza Report

0

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)));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!