CodeStates / 문자열다루기

WeWorship TV·2020년 7월 16일
0
  • index로 접근은 가능하지만 쓸 수는 없음(read-only)
  • 문자열에는 +연산자를 사용할 수 있음
  • string 타입과 다른 타입 사이에 + 연산자를 쓰면 string 형식으로 변환 (toString)
	var str1 = 'Code';
	var str2 = "States";
	var str3 = '1';

	console.log(str1 + str2);  // 'CodeStates'
	console.log(str3 + 7);     // '17'
- str1.concat(str2, str3, ....)의 형태로도 사용 가능

length PROPERTY

  • 문자열의 전체 길이를 변환

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('Blue');  // 5
- see more: str.includes(searchValue)
  Internet Explorer와 같은 구형 브라우저에서는 작동하지 않으므로 주의
  
**str.split(seperator)**
- arguments : 분리 기준이 될 문자열
- return value : 분리된 문자열이 포함된 배열

```javascript
	var str = 'Hello from the other side';
	console.log(str.split(' '));
	// ['Hello', 'from', 'the', 'other', 'side]
  • csv 형식을 처리할 때 유용

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 범위를 초과하면 마지막까지 출력
  • see more : str.slice(start, end)
    substring과 비슷하나, 몇가지 차이점을 보임

str.toLowerCase() / str.toUpperCase()

  • arguments : 없음
  • return value : 대, 소문자로 변환된 문자열
	console.log('ALPHABET'.toLowerCase());
	// 'alphabet'
	console.log('alphabet'.toUpperCase());
	// 'ALPHABET'
  • 단, 모든 string method는 변하지 않음
  • array method는 immutable 및 mutable 여부를 잘 기억해야 함
profile
자 이제 시작이야 내 꿈을

0개의 댓글