-
문자열 메소드 (string method)concept/javascript 2020. 3. 26. 21:28
indexOf(searchvalue)
return value : 처음으로 찾고자 하는 문자열 (없으면 -1 을 반환)
lastIndexOf 는 문자열 뒤에서 부터 찾음
'Blue Whale'.indexOf('Blue'); //0 'Blue Whale'.indexOf('blue'); //-1 'Blue Whale'.indexOf('Whale'); //5 'Blue Whale Whale'.indexOf('Whale'); //5 --> 처음으로 일치하는 index만 찾는다. 'canal'.lastIndexOf('a'); //3 --> 문자열 뒤에서 부터 찾는다.
str.split(seperator)
arguments : 분리 기준이 될 문자열
return value : 분리된 문자열이 포함된 array
csv 형식을 처리할 때 유용 (comma seperate value)
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 사이의 문자열
str.slice(start, end) 와 비슷하나 몇 가지 차이점이 있다!
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로 취급
str.toLowerCase() / str.toUpperCase()
immutable
arguments : 없음
return value : 대, 소문자로 변환된 문자열
console.log('ALPHABET'.toLowerCase()); // 'alphabet' console.log('alphabet'.toUpperCase()); // 'ALPHABET'
let word = 'hello'; console.log(word.toUpperCase()); //--> 'HELLO' console.log(word); //--> 'hello' ** 이 method 는 immutable 하다!
trim()
문자열 좌우에서 공백을 제거하는 함수
var str = " test "; console.log(":" + str.trim() + ":"); //->:test: console.log(":" + str.ltrim() + ":"); //->:test : console.log(":" + str.rtrim() + ":"); //->: test:
String. match()
문자열이 정규식과 매치되는 부분을 검색
var str = 'red is impressive.' str.match('red'); //-->["red", index: 0, input: "red is impressive.", groups: undefined]
String.replace()
어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?'; const regex = /dog/gi; console.log(p.replace(regex, 'ferret')); // expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?" console.log(p.replace('dog', 'monkey')); // expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"
'concept > javascript' 카테고리의 다른 글
Mutable vs Immutable (0) 2020.03.27 정규표현식(regular expression) (0) 2020.03.27 객체 (Object) (0) 2020.03.26 함수와 메소드의 차이(Difference between function and method) (0) 2020.03.25 배열, 반복문(for, while) (0) 2020.03.25