복습 #2-1 문자열 다루기

Joshua Song / 송성현·2019년 11월 19일
0

프리코스_35

목록 보기
5/15

Introduction

두 번째 복습 토픽은 문자열 다루기이다. 문자열은 영어로 String이고 당연히! Primitive Type이다. 지조가 있다. 이번 포스팅에는 String의 여러 Method를 복습할 것이다. 웬만한 거는 기억나지만 그래도 하도 종류가 많다보니 나도 구글링/MDN의 도움을 받지만...

포스팅을 통해 한번 더 익숙해질 기회이다!

String 관련 정보

String 접근하기

String[index]를 통해 string의 몇 번째 캐릭터를 읽을 수 있다. You cannot edit or write. It is read only.

Example)
  let example = "Chicken";
  example[2] = "i"

String 이어주기 (+ or String.concat)

String은 +를 사용하면 다른 종류라도 바로 String으로 만들어 이어줄 수 있다. 엄청나게 유용한, String에만 있는 것이다. Concat이라는 String Method가 존재하지만...+라는 압도적 강자 때문에 String에서는 잘 사용하지 않는다.

Example)
  let part1 = "Coca"
  let part2 = "Cola"
console.log(part1 + part2);
//Expected Outcome: "CocaCola"
console.log(part1.concat(" ", part2);
//Expected Outcome: "Coca Cola"

String의 길이 구하기. (String.length)

간단하다. String.length를 하면 바로 길이가 나온다. 엄청 많이 사용한다...

Example)
let giveme = "Ineedsleep";
console.log(giveme.length);
//Expected Outcome: 10

String 속 찾고자하는 것의 index 구하기

(String.indexOf & lastIndexOf)

일단 argument로는 String 속 찾고자 하는 것이 들어간다. 뭐가 됐든간에 String에 찾고자 하는 게 있다면 그것의 index를 return해줄 것이다.
lastIndexOf는 뒤에서 부터 찾기 때문에 같은 것이 겹칠 경우 뒤에 있는 것을 return한다. indexOf는 앞에서 부터 찾는다. 찾는 것이 없을 경우 -1을 return 한다.

String.includes는 index를 찾기 보다는 string안에 있는지 없는지 만 확인한 후 true 아니면 false를 리턴한다. 꿀팁~

Example)
let food = "Chicken Nugget";

console.log( food.indexOf("k") );
//Expected Outcome: 4
console.log( food.lastIndexOf("g") );
//Expected Outcome: 11
console.log( food.indexOf("Nugget") );
//Expected Outcome: 8 
//Nugget이 시작하는 index를 return 한다!
console.log( food.includes("x") );
//Expected Outcome: false

String을 나누고 싶을 때! (String.split)

String을 배열로 캐릭터 하나씩 나누고 싶을 때 사용한다. csv (comma-separated variables) 를 처리할 때 유용하게 쓰인다. 정보를 쉼표로 나누어 나열할 때 사용한다.

Example)
let car = "Bentley";
console.log(car.split(""));
//Expected Outcome: ["B", "e", "n", "t", "l", "e", "y"]

String을 자르기 (String.slice or String.substring)

String을 원하는 길이로, 몇번 째 index에서 몇번 째 까지로 자르고 싶을 때 사용할 수 있는 method는 두가지이다. slice와 substring인데 두가지 method는 비슷한듯 하지만 다르다. 일단 기본적으로 slice와 substring 둘다 start와 end를 매개변수로 다룬다. end는 선택옵션이다. 차이점과 공통점을 구분해보도록 한다.

string.slice(beginIndex, [, endIndex]) vs string.substring(indexStart, [, indexEnd])

  1. 매개변수로 음수가 들어올 경우:
  • slice: string의 길이에 음수를 더한 값으로 계산한다. 예를 들어 길이가 8인 string을 string.slice(-7, -3)을 할 경우 각자 항목을 8에 더해줘 string.slice(1, 5)가 된다.
  • substring: 0으로 취급한다.
  1. 끝 index가 없는 경우:
    두 method다 가장 끝의 캐릭터 까지 계산한다.

  2. 시작 index보다 끝 index가 클 경우:

  • slice: 빈 문자열을 반환한다.
  • substring: 시작과 끝 index를 바꿔서 계산한다.
  1. 시작 index가 string길이보다 길거나 시작과 끝 index가 같을 경우:
  • 빈 문자열을 반환한다.

*substr 이라는 method도 찾아보니 있는데 mdn에 보니...그래서 slice와 substring만 사용할 것이다.

Warning: Although String.prototype.substr(...) is not strictly deprecated ( as in "removed from the Web standards"), it is considered a legacy function and should be avoided when possible. It is not part of the core JavaScript language and may be removed in the future. If at all possible, use the substring() method instead.

문자열 파트 1 끝.

profile
Grow Joshua, Grow!

0개의 댓글