Gunal Bondre
Gunal Bondre

Reputation: 94

Each letter once uppercase

javascript function which returns an array of string in such a way that it contains all possible upper-case letters of the input string one at a time sequentially.

uppercase("hello") ➞ ["Hello", "hEllo", "heLlo", "helLo", "hellO"]

what i have tried is

const helloCapital = (str) => {
  let a = [];
  for (let i in str) {
    a.push(str[i].toUpperCase() + str.slice(1));
  }
  return a;
};

but it gives weird results

[ 'Hello', 'Eello', 'Lello', 'Lello', 'Oello' ]

Upvotes: 2

Views: 87

Answers (3)

Mestre San
Mestre San

Reputation: 1915

This looks like a challenge for a course or challenges website.

If that is the case, it is really, really not cool to come here and ask for that answer.

But, since I'm already here, here it goes a working solution.

const capitals = s => Array.from(s,(_,i)=>s.slice(0,i)+_.toUpperCase()+s.slice(i+1))

UPDATE: Explaining the code

Array.from works on iterable objects, such as strings, Arrays and, ArrayLike objects for example.

It calls the function you pass as the first argument on each element of the iterable, in this case, the string.

The function receives 1 element of the iterable (the _) and the position of that element (the i)

So the function is returning a concatenation of 3 things: * the substring of the original string from 0 to i * the current element of the iterable, or current character, toUpperCase() * the substring of the original string from i+1 to the end of the string.

Upvotes: 3

Azad
Azad

Reputation: 5264

use array array map,

var str = "hello";

var capitals = Array.from(str).map((e, i, ar) => {

  let r = [...ar];
  r[i] = ar[i].toUpperCase();
  return r.join('');
});

console.log(capitals)

Upvotes: 0

VitorLuizC
VitorLuizC

Reputation: 354

Your logic is wrong, to work you need to concat the slice before letter with capitalized letter and with the slice after letter.

function capitalizeEachLetter (text) {
  return Array.from(text, (letter, index) =>
    text.slice(0, index) + letter.toUpperCase() + text.slice(index + 1)
  );
}

Upvotes: 0

Related Questions