Home > database >  How to use javascript to turn the first letter to uppercase? First letter of each word
How to use javascript to turn the first letter to uppercase? First letter of each word

Time:02-04

enter image description here

I'm fetching some random pictures with their tag name inside an array. Each array has up to 3 or 4 tag names. I only need a tag name out of each arrays (which was accomplished already, those in red circle). Now I want to turn the first letter of each word to uppercase (something like this--"Chicago"). I don't mind if I have to rewrite the methods. Your ideas and solution would be appreciated. Thanks in advance

CodePudding user response:

You don't need any JS for this, css is enough :

.capitalize{
  text-transform: capitalize;
}

Apply this class to turn each first word's letter to capital.

MDN link for text-transform

CodePudding user response:

You could always use CSS on the p element: text-transform: capitalize;

or

Could convert the output to string and the apply the css property.

CodePudding user response:

Seeing as the question specifically asks for a JavaScript solution, you can do this by splitting up the string into words and using toUpperCase()

function capitaliseWords(input) {
  const words = input.split(' '); // split up the string into an array of words
  const newWords words.map((word) => {
    // map each word to its capitalised form
    return `${word[0].toUpperCase}${word.slice(1)}`
  }):
  // rebuild to a single string and return
  return newWords.join(' ');
}

CodePudding user response:

{mydata.map((data, index) => (
        <>
          <img src="img.png" alt="image goes here" />
          <p>{data.split('')[0].toUpperCase()   data.slice(1, data.length)}</p>
        </>
 ))}
  •  Tags:  
  • Related