E
E
Evgeniy2021-07-09 23:04:33
JavaScript
Evgeniy, 2021-07-09 23:04:33

Can you please explain what is happening in that function?

Good afternoon

There is a code that capitalizes every first letter in a phrase

here is the code

const word = (str) => {
  let result = '';
  for (let i = 0; i < length(str); i += 1) {
    console.log(str[i]); 
    
    const world = str[i] !== ' ' && (i === 0 || str[i - 1] === ' ');
    result += world ? toUpperCase(str[i]) : str[i];
    
  }

return result;
};

document.write(word('просто рандомная фраза'));



Everything works fine, but it is not clear what is happening in these lines:
const world = str[i] !== ' ' && (i === 0 || str[i - 1] === ' ');
result += world ? toUpperCase(str[i]) : str[i];


Please explain more specifically, I want to understand ...

P / s: This code is taken from the lesson, and it works there, but not in the sandbox, for the sandbox, I rewrote it a little, but it didn’t become clearer
const word = (str) => {
  let result = '';
  for (let i = 0; i < str.length; i += 1) {
    console.log(str[i]); 
    
    const current = str[i] !== ' ' && (i === 0 || str[i - 1] === ' ');
 
    result += current ? str[i].toUpperCase() : str[i];
    
  }

return result;
};

document.write(word('просто рандомная фраза'));

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2021-07-09
@Zheleznov

// это условие, при котором букву надо делать большой
const world = str[i] !== ' ' && (i === 0 || str[i - 1] === ' ');

// здесь добавляется либо заглавная, либо просто-как-есть буква,
// в зависимости от условия выше
result += world ? toUpperCase(str[i]) : str[i];

The condition is parsed like this: the
current letter is not a space str[i] !== ' '
AND it is the first letter in the string i === 0OR the previous character is a space str[i - 1] === ' '
The bad thing here is that non-first letters are not handled in any way. From the string "habraHabr" you get "HabraHabr", although it would probably be more correct "Habrahabr"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question