푸린세스

Capitalize Exercise : 문자열함수 slice(), substring() 본문

프론트/자바스크립트

Capitalize Exercise : 문자열함수 slice(), substring()

푸곰주 2023. 5. 30. 12:17
const str = 'Mozilla';

console.log(str.substring(1, 3));
// Expected output: "oz"

console.log(str.substring(2));
// Expected output: "zilla"​
Capitalize Exercise

Define a function called capitalize that accepts a string argument and returns a new string with the first letter capitalized (but the rest of the string unchanged).  For example:

  1. capitalize('eggplant') // "Eggplant"
  2. capitalize('pamplemousse') // "Pamplemousse"
  3. capitalize('squid') //"Squid"

Hints:

  • Remember that strings are immutable, meaning that you cannot simply change the first letter in the original string.  You will need to make a new string that you return.
  • Single out the first letter and capitalize it. (use a string method to help!)
  • Add that first letter to the rest of the original string, sliced to omit the original first letter (use a string method to help!)
  • For example: 'eggplant' becomes 'E' + 'ggplant'
// DEFINE YOUR FUNCTION BELOW:

function capitalize(str){
    let result = '';
    for(let i=1; i<str.length; i++){
        
        result += str[i];
        
    }
    return str[0].toUpperCase() + result;
}​
function capitalize(word) {
    return word[0].toUpperCase() + word.slice(1); // == word.substring(1);
    // return `${word[0].toUpperCase()}${word.slice(1)}`; ==> 템플릿 리터럴
}

console.log(capitalize('eggplant'));
console.log(capitalize('pamplemousse'));
console.log(capitalize('squid'));

 문자열함수 slice(), substring() 를 이용해서 푸심

내가 쓰는방법과다름

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

 

Array.prototype.slice() - JavaScript | MDN

slice() 메서드는 어떤 배열의 begin 부터 end 까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 바뀌지 않습니다.

developer.mozilla.org

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/substring

 

String.prototype.substring() - JavaScript | MDN

substring() 메소드는 string 객체의 시작 인덱스로 부터 종료 인덱스 전 까지 문자열의 부분 문자열을 반환합니다.

developer.mozilla.org

String.prototype.slice()

slice() 메소드는 문자열의 일부를 추출하면서 새로운 문자열을 반환합니다

 

const str = 'The quick brown fox jumps over the lazy dog.';

console.log(str.slice(31));
// Expected output: "the lazy dog."

console.log(str.slice(4, 19));
// Expected output: "quick brown fox"

console.log(str.slice(-4));
// Expected output: "dog."

console.log(str.slice(-9, -5));
// Expected output: "lazy"

String.prototype.substring()

substring() 메소드는 string 객체의 시작 인덱스로 부터 종료 인덱스 전 까지 문자열의 부분 문자열을 반환합니다.

 

 

const str = 'Mozilla';

console.log(str.substring(1, 3));
// Expected output: "oz"

console.log(str.substring(2));
// Expected output: "zilla"