JavaScript - String Methods

LANA·2020년 4월 6일
0

JavaScript

목록 보기
2/21
post-thumbnail

BASIC USAGES - ACCESSING A CHARACTER

  • str[index]
var str = 'CodeStates';
console.log(str[0]);  // 'C'
console.log(str[4]);  // 'S'
console.log(str[10]); // undefined

Note : index로 접근은 가능하지만 쓸 수는 없음 (read-only)

str[0] = 'G';
console.log(str); // 'CodeStates' not 'GodeStates'

BASIC USAGES - CONCATENATING STRINGS

  • + 연산자를 쓸 수 있음
  • string 타입과 다른 타입 사이에 + 연산자를 쓰면, string 형식으로 변환(toString)
    • str1.concat(str2, str3...); 의 형태로도 사용 가능
var str1 = 'Code';
var str2 = "States";
var str3 = '1';
console.log(str1 + str2); // 'CodeStates'
console.log(str3 + 7);    // '17'

length PROPERTY

  • 문자열의 전체 길이를 반환
var str = 'CodeStates';
console.log(str.length); // 10

str.indexOf(searchValue)

  • arguments: 찾고자 하는 문자열
  • return value: 처음으로 일치하는 index, 찾고자 하는 문자열이 없으면 -1
  • lastIndexOf는 문자열 뒤에서 부터 찾음
'Blue Whale'.indexOf('Blue');        // 0
'Blue Whale'.indexOf('blue');        // -1
'Blue Whale'.indexOf('Whale');       // 5
'Blue Whale Whale'.indexOf('Whale'); // 5

'canal'.lastIndexOf('a');            // 3
  • see more: str.includes(searchValue)
    • Internet Explorer와 같은 구형 브라우저에서는 작동하지 않으므로 주의

str.split(seperator)

  • arguments: 분리 기준이 될 문자열
  • return value: 분리된 문자열이 포함된 배열
    • csv 형식을 처리할 때 유용
var str = 'Hello from the other side';
console.log(str.split(' '));
// ['Hello', 'from', 'the', 'other', 'side']

str.substring(start, end)

  • arguments: 시작 index, 끝 index
  • return value: 시작과 끝 index 사이의 문자열
var str = 'abcdefghij';
console.log(str.substring(0, 3));  // 'abc'
console.log(str.substring(3, 0));  // 'abc'
console.log(str.substring(1, 4));  // 'bcd'
console.log(str.substring(-1, 4)); // 'abcd', 음수는 0으로 취급
console.log(str.substring(0, 20)); // 'abcdefghij', index 범위를 넘을 경우 마지막 index로 취급
  • see more: str.slice(start, end)
    • 문자열/배열 잘라내는 기능
    • substring과 비슷하나, 몇가지 차이점을 보임
  • see more: array.splice
    • 배열 중간에 값 삽입/삭제

배열에 element 넣고 빼기 (push, pop, shift, unshift)

  • arr.unshift() : 앞쪽에 element 추가
  • arr.shift() : 앞쪽의 element 삭제
  • arr.push(sth): 뒤쪽에 element 추가
  • arr.pop(): 뒤쪽의 element 삭제

str.toLowerCase() / str.toUpperCase() -IMMUTABLE

  • arguments: 없음
  • return value: 대,소문자로 변환된 문자열
console.log('ALPHABET'.toLowerCase()); // 'alphabet'
console.log('alphabet'.toUpperCase()); // 'ALPHABET'

WHAT IS 'IMMUTABLE'?

  • 모든 string method는 immutable
  • 즉, 원본이 변하지 않음
  • array method는 IMMUTABLE 및 MUTABLE 여부를 잘 기억해야 함

LEARN YOURSELF
trim
공백 문자: 탭 문자 (\t), Carrige return(\r\n) 및 return 문자(\n)
match (advanced)
replace (advanced)
정규 표현식 (advanced)

profile
Let's code like chord !

0개의 댓글