본문 바로가기
웹 개발/javascript

[TIL] 문자열(String) 메소드: length, indexOf, substring, slice, split, includes, toLowerCase(), toUpperCase(),

by 스토리라이언 2021. 3. 3.

2021.3.3

str[index] : 한 글자씩 index의 글자를 가져온다. 

let str = 'hello world';

console.log(str[0]); //h
console.log(str[1]); //e
console.log(str[100]); //undefined

concatenating strings: + 연산자를 통해 string 타입과 다른 타입을 +연산자를 통해 concat할 경우 string 타입으로 변환된다.

let str1 = 'hello';
let str2 = 'world';

console.log(str1+str2); //helloworld

console.log(1+'1'); // 11

console.log(str1+'3'); hello3

 

str.length: 문자열의 전체 길이를 반환한다. 

'hello'.length; //5

let a = 'world';
a.length; //5

 

str.indexOf(searchValue) : 인수로 전달받은 문자열을 검색하여 첫번째 인덱스를 반환한다. 

let b = 'hello world';

b.indexOf('l'); // 2
b.indexOf('or'); // 7
b.indexOf('x'); // -1 : 찾는 값이 없으면 -1를 리턴한다. 

indexOf는 대상 문자열에 특정 문자열이 존재하는지 확인할 때 유용하다.

if(str.indexOf('Hello') !== -1) { //문자열 str에 'Hello'가 없다면
  //str에 Hello가 있는 경우 처리할 내용
}

이런 경우 includes메소드를 사용하면 보기 더 편하다.

if(str.includes('Hello')) {
 //str에 'Hello'가 포함된 경우 실행할 내용
}

 str.includes: 대상 문자열에 인수로 전달받은 문자열이 포함되어 있는지 확인하여 그 결과를 true, false로 반환한다.

let str = 'hello world';

str.includes('hello'); //true
str.includes('h'); //true
str.includes(''); //true
str.includes('x'); //false

//2번째 인수로 검색을 시작할 인덱스를 전달할 수 있다.
str.includes('l', 3); //true
str.includes('h', 3); //false

str.lastIndexOf(searchValue[, fromIndex]); 주어진 값과 일치하는 부분을 fromIndex로부터 역순으로 탐색하여, 최초로 마주치는 인덱스를 반환합니다. 일치하는 부분을 찾을 수 없으면 -1을 반환합니다.

str.lastIndexOf(searchValue[, fromIndex])

'canal'.lastIndexOf('a');     //  3 반환
'canal'.lastIndexOf('a', 2);  //  1 반환

 

str.split(seperator) : 인자는 분리 기준이 되는 문자열이다.  반환값은 배열이다

let str2 = "where are you going?";

str2.split(' '); //공백으로 단어를 구분한다.
// ["where", "are", "you", "going?"]
str2.split(''); //빈 문자열이면 각 문자를 모두 분리
// ["w", "h", "e", "r", "e", " ", "a", "r", "e", " ", "y", "o", "u", " ", "g", "o", "i", "n", "g", "?"]
str2.split(); //인수를 생략하면 문자열 전체를 리턴한다
// ["where are you going?"]

//두번째 인수로 배열의 길이를 지정할 수 있다. 
str2.split(' ', 3); // ["where", "are", "you"]

 

str.substring(start, end) : start인자부터 end 인자로 전달받은 인덱스에 위치하는 문자 바로 전까지 부분 문자열을 반환한다. 

let str = 'hello world';
//인덱스 1부터 인덱스 4이전까지 부분 문자열을 반환
str.substring(1,4); // "ell" 

//두번째 인수는 생략될 수 있다. 그런 경우 start부터 문자열 끝까지 반환한다
str.substring(1);  // "ello world"

//첫번째 인수 > 두번째 인수인 경우 두 인수는 교환된다. 
str.substring(4,1); // "ell"

//인수 < 0 인 경우 0으로 취급
str.substring(-3); // 'hello world'

//인수>문자열의 길이 인 경우 문자열의 길이로 취급된다. 
str.substring(1,100); // "ello world"
str.substring(100); // ""

 

str.slice(start, end): substring과 유사. slice는 음수인 인자를 전달할 수 있다. 

('hello world').substring(0,5); //"hello"
('hello world').slice(0,5); //"hello"

//substring의 인자가 음수이면 0으로 취급한다.
str.substring(-5); // 'hello world'

//slice는 음수를 인자로 전달할 수 있다. 뒤에서 5자리를 잘라서 반환한다
str.slice(-5); //'world'

 

str.toLowerCase(): 소문자로 변환

str.toUpperCase(): 대문자로 변환

console.log('hello'.toUpperCase()); // HELLO

console.log('HELLO'.toLowerCase()); // hello

 

댓글