Languages
[Edit]
EN

JavaScript - first letter of each word lowercase

0 points
Created by:
Jan-Alfaro
711

In this article, we would like to show you how to make the first letter of each word lowercase in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

var text = 'This Is Example Text...';

const array = text.split(' ');

for (let x = 0; x < array.length; ++x) {
    array[x] = array[x].charAt(0).toLowerCase() + array[x].slice(1);
}
var result = array.join(' ');

console.log(result);

 

Practical example

In this example, we make the first letter of each word uppercase using:

  1. split() method split the text into an array of separate words,
  2. charAt() method with toUpperCase() to uppercase the first letter of each word,
  3. slice() method to get the rest of the word - without the first letter, so we can add it to the uppercase letter.
  4. join() method to convert the array back to the string.
// ONLINE-RUNNER:browser;

function lowercase(text) {
    var array = text.split(' ');

    for (var x = 0; x < array.length; ++x) {
        array[x] = array[x].charAt(0).toLowerCase() + array[x].slice(1);
    }
    return array.join(' ');
}


// Usage example:

console.log(lowercase('This Is Example Text...'));

Output:

this is example text...

Modern syntax - reusable arrow function

In this section, we present a solution that is equal to the above one but written in modern syntax.

// ONLINE-RUNNER:browser;

const lowercase = (text) => {
    const array = text.split(' ');

    for (let x = 0; x < array.length; ++x) {
        array[x] = array[x].charAt(0).toLowerCase() + array[x].slice(1);
    }
    return array.join(' ');
};


// Usage example:

console.log(lowercase('This Is Example Text...'));

Output:

this is example text...

References

  1. String.prototype.split() - JavaScript | MDN
  2. String.prototype.charAt() - JavaScript | MDN
  3. String.prototype.toLowerCase() - JavaScript | MDN
  4. String.prototype.slice() - JavaScript | MDN
  5. Array.prototype.join() - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join