๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“‚ Base/์•Œ๊ณ ๋ฆฌ์ฆ˜

๋ฌธ์ž์—ด์„ ๊ตฌ์„ฑํ•˜๋Š” ๊ฐ ๋‹จ์–ด์˜ ์ฒซ ๊ธ€์ž๊ฐ€ ๋Œ€๋ฌธ์ž์ธ ๋ฌธ์ž์—ด์„ ๋ฆฌํ„ดํ•˜๊ธฐ

by Dev. Ella 2023. 3. 21.

๐Ÿ“œ ๋ฌธ์ œ

๋ฌธ์ž์—ด์„ ์ž…๋ ฅ๋ฐ›์•„ ๋ฌธ์ž์—ด์„ ๊ตฌ์„ฑํ•˜๋Š” ๊ฐ ๋‹จ์–ด์˜ ์ฒซ ๊ธ€์ž๊ฐ€ ๋Œ€๋ฌธ์ž์ธ ๋ฌธ์ž์—ด์„ ๋ฆฌํ„ดํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

 

โš ๏ธ ์ฃผ์˜์‚ฌํ•ญ

- ๋‹จ์–ด๋Š” ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„ํ•ฉ๋‹ˆ๋‹ค.
- ์—ฐ์†๋œ ๊ณต๋ฐฑ์ด ์กด์žฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
- ๋นˆ ๋ฌธ์ž์—ด์„ ์ž…๋ ฅ๋ฐ›์€ ๊ฒฝ์šฐ, ๋นˆ ๋ฌธ์ž์—ด์„ ๋ฆฌํ„ดํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

 

โœ๐Ÿป ๋‚ด ํ’€์ด

function letterCapitalize(str) {
  // ์ž…๋ ฅ: str
  // ์ถœ๋ ฅ: ๋ฌธ์ž์—ด์„ ๊ตฌ์„ฑํ•˜๋Š” ๊ฐ ๋‹จ์–ด๋“ค์˜ ์ฒซ ๊ธ€์ž๊ฐ€ ๋Œ€๋ฌธ์ž๋กœ ๋œ ๋ฌธ์ž์—ด ๋ฆฌํ„ด

  // ๋น„์–ด์žˆ๋Š” ๋ฐฐ์—ด์„ ๋งŒ๋“ค๊ณ , ์ „๋‹ฌ๋ฐ›์€ ๋ฌธ์ž์—ด์„ space๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๊ฐ ๋‹จ์–ด๋กœ ์ž˜๋ผ, ๋ฐฐ์—ด์— ์ €์žฅ
  let words = str.split(' ');

  // ์œ„์˜ ๋ฐฐ์—ด์„ ๋ฌธ์ž์—ด ๊ธธ์ด๊นŒ์ง€ for loop๋ฅผ ๋Œ๋ ค 
  for (let i = 0; i < words.length; i++) {
    // ๊ฐ ๋‹จ์–ด์˜ ์ฒซ๊ธ€์ž๋ฅผ ๋Œ€๋ฌธ์ž๋กœ ๋ณ€ํ™˜
    // ๋Œ€๋ฌธ์ž์ธ ์ฒซ ๊ธ€์ž + ๊ทธ ๋‹ค์Œ ๊ธ€์ž๋“ค์„ ๋ถ™์—ฌ ๋ฐฐ์—ด์˜ ๊ฐ ๋‹จ์–ด๋ฅผ ์—…๋ฐ์ดํŠธ
    if (words[i].length > 0) {
      words[i] = words[i][0].toUpperCase() + words[i].substr(1);
    }
  }
  // ๊ฐ ๋‹จ์–ด ์‚ฌ์ด์— ์ŠคํŽ˜์ด์Šค ์ถ”๊ฐ€ ํ›„ ํ•ฉ์ณ, ๋ฌธ์žฅ์œผ๋กœ ์น˜ํ™˜ํ•˜์—ฌ ๋ฆฌํ„ด
  str = words.join(' ');
  return str;
}

 

๐Ÿ’ก ์•Œ์•„๋‘๋ฉด ์ข‹์„ ๊ฐœ๋…

substr( )

substr( ) ๋ฉ”์†Œ๋“œ๋Š” ๋ฌธ์ž์—ด์—์„œ ํŠน์ • ์œ„์น˜์—์„œ ์‹œ์ž‘ํ•˜์—ฌ ํŠน์ • ๋ฌธ์ž ์ˆ˜๋งŒํผ์˜ ๋ฌธ์ž๋“ค์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค. (์ถœ์ฒ˜: mdn)

const str = 'Mozilla';

console.log(str.substr(1, 2)); // 'oz': index 1๋ถ€ํ„ฐ 2๊นŒ์ง€
console.log(str.substr(2)); // 'zilla': index 2๋ถ€ํ„ฐ ๋๊นŒ์ง€
console.log(str.substr(-3, 2)); // 'll': ๋์—์„œ๋ถ€ํ„ฐ 3๋ฒˆ์งธ๋ถ€ํ„ฐ 2๊ธ€์ž

 

toUpperCase( )

toUpperCase( ) ๋ฉ”์†Œ๋“œ๋Š” ๋ฌธ์ž์—ด์„ ๋Œ€๋ฌธ์ž๋กœ ๋ณ€ํ™˜ํ•œ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค. JavaScript ๋ฌธ์ž์—ด์€ ๋ถˆ๋ณ€ํ•˜๋ฏ€๋กœ ์›๋ณธ ๋ฌธ์ž์—ด์—๋Š” ์˜ํ–ฅ์„ ์ฃผ์ง€ ์•Š๋Š”๋‹ค. (์ถœ์ฒ˜: mdn)

console.log('alphabet'.toUpperCase()); // 'ALPHABET'

 

๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป ๋ฐฐ์šด ์ 

์ฒซ ๋ฒˆ์งธ ๊ธ€์ž๋ฅผ ๋Œ€๋ฌธ์ž๋กœ ๋ณ€ํ™˜ ํ›„, substr( ) ๋ฉ”์†Œ๋“œ๋กœ ์ฒซ ๋ฒˆ์งธ ๊ธ€์ž ๋‹ค์Œ์˜ ๊ธ€์ž๋“ค์„ ์ด์–ด ๋ถ™์ด๊ณ , ๊ฐ ๋‹จ์–ด๋“ค์„ join( ) ๋ฉ”์†Œ๋“œ๋กœ ์ด์–ด ๋ถ™์—ฌ์„œ ๋ฆฌํ„ดํ•œ๋‹ค. ์—ญ์‹œ ๋ฉ”์†Œ๋“œ๋“ค์˜ ์†์„ฑ๊ณผ ํ™œ์šฉ๋ฒ•์„ ์ž˜ ์•Œ์•„์•ผ ์ ์žฌ์ ์†Œ์— ์“ธ ์ˆ˜ ์žˆ๋‹ค. 

๋”๋ถˆ์–ด, words[i].substr(1) ๋ฅผ ์“ฐ๋Š”๋ฐ ์†Œ๊ด„ํ˜ธ ( )๋ฅผ ์‹ค์ˆ˜๋กœ ๋Œ€๊ด„ํ˜ธ [ ] ๋กœ ์จ์„œ ํ…Œ์ŠคํŠธ๊ฐ€ ํ†ต๊ณผ๋˜์ง€ ์•Š์•˜๋‹ค. ์ฝ”๋“œ๋ฅผ ๋งŽ์ด ์จ์„œ ์†์— ๋งŽ์ด ์ตํ˜€๋†”์•ผ ์ž์ž˜ํ•œ ์‹ค์ˆ˜๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™๋‹ค.

๋Œ“๊ธ€