p r o g r a m m i n g

3일차 / JS 문자열

hee.hee 2022. 4. 27. 18:10

문자 접근 방법


str[indexnumber]

str[접근할 글자의 위치]의 형태로 사용.

str을 배열과 같은 오브젝트로 취급하려, 문자에 해당하는 숫자 인덱스를 사용함.

단, 이 접근법을 이용해 수정은 불가하고 배열로 저장되지 않는다.

read-only

 

str.chartAt( )

메서드. ( ) 안에는 접근할 글자의 위치가 들어감.

위의 방법과 같이 글자 위치는 0부터 센다.

 

 

 

 

 

문자열 변환


문자열을 다른 타입과 '+ '로 함께 쓰면 결과가 string으로 변환

Stinrg( )

`${}`

+ concat ?

 

 

 

 

 

 

문자열 프로퍼티, 메서드, 함수


 

str.length

문자열 전체 길이 반환

 

 

 

 

str.indexOf(searchvalue, position)

str.indexOf(찾을 문자열, 검색 시작 위치)

searchvalue는 필수값, position은 옵션값이다.

찾고자하는 문자열이 몇번째 글자부터인지 반환.

찾는 문자열이 없으면 -1 반환

lastIndexOf. 뒤부터 검색

const str = "sherlock";

str.indexOf("lock"); //4
str.indexOf("she", 1); // -1
str.indexOf("she", 0); //0

 

 

 

 

str.substring(start, end)

argument: 검색 시작 index / 끝 index

return: 시작과 끝 index 사이 문자열

(1,5) -> 1, 2,3,4 번째 문자 반환

음수는 0으로, 인덱스 초과는 마지막 글자로 적용 됨

stri.substring(0,4);
//sher

stri.substring(8,0);
// sherlock

stri.substring(3,4);
// r

 

 

 

 

str.split(seperator)

argument: 분리 기준이 될 문자열

return value: 배열의 형태

split된 상태로 저장됨

+ split과 slice의 차이를 모르겠다. 아래 블로그와 원문 참고하기

https://velog.io/@chloeee/Slice-vs-Splice-vs-Split%EC%9D%98-%EC%B0%A8%EC%9D%B4%EC%A0%90

 

 

 

 

 

csv.split('\n')

줄바꿈. csv에서 사용.

 

 

 

 

str.toLowerCase()

str.toUpperCase()

대소문자 변환

(immutable. 원본이 변하지 않음)

 

 

 

 

 

 

 

 

어려웠던 문제, 새로 알게된 것


Math.floor( )

내림, 버림. 비슷한 다른 함수들 정리할 필요가 있음.

 

Math.min( )

최소값 검색

 

Math.abs( )
절대값 구하기

 

 

 

 

가장 짧은 단어 리턴하기

https://urclass.codestates.com/codeproblem/a5ac1e78-e9ec-4cf1-96f8-bb10f68b5c01

// reference

function findMinLengthOfThreeWords(word1, word2, word3) {
  let shortestLen = word1.length;

  // 첫 번 째 글자가 2번째 글자보다 길 때
  if (word1.length > word2.length) {
    shortestLen = word2.length;
    // word 2 랑 word 3을 비교
    if (word2.length > word3.length) {
      shortestLen = word3.length;
    }
  } else {
    // word1 과 word3 을 비교
    if (word1.length > word3.length) {
      shortestLen = word3.length;
    }
  }
  return shortestLen;
}


//우리가 적은 답
function findMinLengthOfThreeWords(word1, word2, word3) {
  return(Math.min(word1.length, word2.length, word3.length));
}

 

 

 

 

slice 사용

https://urclass.codestates.com/codeproblem/a488075e-00df-46e9-b1fd-abe6d0c57c50

function takeLetters(num, str) {
 if(num >= str.length || str === ''){
   return str;
 }
 else {
   return str.slice(0,num);
 }
}

이해는 가는데 다음에 풀면 또 막힐듯 하다.

풀이법 익숙해지도록 반복해서 보기.

 

 

 

 

 

slice 사용2

function dropLetters(num, str) {
  if (num >= str.length) {
    return '';
  }

  return str.slice(num);
}

 

위의 문제에서는 slice가 0~num 인덱스 만큼 선택되는 거였는데,

여기서는 num개 만큼 삭제하는 용도로 쓰였다.

 

 

 

 

 

 

 

parseInt와 String 의 차이

이건 나중에 알아보고 붙이기.

우리는 String을 썼는데 reference는 parseInt를 썼다.

 

 

 

 

 

 

 

시간 구하기

https://urclass.codestates.com/codeproblem/fb754759-ce33-4906-ac60-c28a2da0b89b

//내 답

function makeLastSeenMsg(name, period) {
  if(period < 60) {
    return `${name}: ${period}분 전에 접속함`;
  }
  else if(period>60 && period<1440){
    let hour = Math.floor(period / 60);
    return `${name}: ${hour}시간 전에 접속함`;
  }
  else if(period>1440){
  let day = Math.floor(period / 1440)
  return `${name}: ${day}일 전에 접속함`;
  }
}
//reference

function makeLastSeenMsg(name, period) {
  const day = 60 * 24;
  const hour = 60;
  if (period >= day) {
    return `${name}: ${Math.floor(period / day)}일 전에 접속함`;
  } else if (period >= hour) {
    return `${name}: ${Math.floor(period / hour)}시간 전에 접속함`;
  } else {
    return `${name}: ${period}분 전에 접속함`;
  }
}

잘풀어서 뿌듯했는데 reference와 풀이 방법이 많이 다르다. 비교하자면 노가다.

다음에 비슷한 풀이 방법이 필요할 때 쓸 수 있도록 해보자