본문 바로가기

프로그래밍/JavaScript

자바스크립트(JavaScript) String.prototype.includes() 폴리필(polyfill)

안녕하세요. 루미오입니다.

JavaScript는 특정 문자열의 포함여부를 확인하는 includes() 함수를 ES6부터 제공하고 있습니다. 현재 IE에서는 사용할 수 없습니다. 물론 indexOf() 함수를 사용해서 특정 문자열이 포함되었는지 찾을 수 있지만, includes() 함수를 사용한다면 코드가 더 명확해지겠지요. 오늘은 includes() 함수의 폴리필을 만들어 보겠습니다.

순서
● String.prototype.includes() 폴리필(polyfill)
● String.prototype.includes() 사용법

하단의 → 코드 확인 및 테스트 버튼을 클릭하면 jsfiddle에서 바로 Test해 보실 수 있습니다.

 

String.prototype.includes() 폴리필

if(!String.prototype.includes) {
	String.prototype.includes = function(search, fromIndex) {
		if(search === undefined || search === null)
			return false;

		search = typeof search === 'number' ? search.toString() : search;

		fromIndex = typeof fromIndex === 'boolean' ? (fromIndex ? 1 : 0) : fromIndex;
		fromIndex = typeof fromIndex === 'number' ? (fromIndex < 0 ? 0 : fromIndex) : 0;

		return this.indexOf(search, fromIndex) !== -1;
	};
}

내부적으로 indexOf() 함수를 사용했습니다.

 

String.prototype.includes() 사용법

/* includes() : 특정 문자열이 포함되었는지 확인 하기 */
var result = false;
var str = 'foo 123 bar';	// str.length : 11

result = str.includes('foo');		// true
result = str.includes('bar');		// true
result = str.includes('BAR');		// false : 대소문자 구분
result = str.includes('hoho');		// false : 'hoho'는 없음
result = str.includes('bar', 7);	// true : 8 index부터 'bar' 시작
result = str.includes('bar', 8);	// true : 8 index부터 'bar' 시작
result = str.includes('bar', 9);	// false : 8 index부터 'bar' 시작
result = str.includes('123', 4);	// true : 4 index부터 '123' 시작
result = str.includes(123, 4);		// true : 숫자도 문자로 동일하게 처리함.

includes() 함수는 문자열이 특정 문자열을 포함하고있는지를 boolean 값으로 return 합니다. 대소문자를 구분하며, 시작 index를 지정할 수 있습니다. 또한 숫자도 문자와 동일하게 찾아줍니다.

 

감사합니다.

- 루미오 . LOOMIO -