본문 바로가기

프로그래밍/JavaScript

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

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

JavaScript는 특정 문자열로 끝나는지 확인하는 endsWith() 함수를 ES6부터 제공하고 있습니다. 현재 IE에서는 사용할 수 없습니다. 물론 lastIndexOf() 함수를 사용해서 특정 문자열로 끝나는지 찾을 수 있지만, endsWith() 함수를 사용하면 코드의 가독성이 좋아지겠지요. 오늘은 ennsWith() 함수의 폴리필을 만들어 보겠습니다.

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

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

 

String.prototype.endsWith() 폴리필

/* String.prototype.endsWith Polyfill */
if(!String.prototype.endsWith) {
	String.prototype.endsWith = function(search, len) {
		if(search === undefined || search === null)
			return false;

		search = typeof search === 'number' ? search.toString() : search;
		len = (len === undefined || len > this.length) ? this.length : len;

		return this.substring(len - search.length, len) === search;
	};
}

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

 

String.prototype.endsWith() 사용법

/* endsWith() : 특정 문자열로 끝나는지 확인 하기 */
var result = false;
var str = 'foo 123 bar';	// str.length : 11

result = str.endsWith('bar');		// true :  'bar'로 끝남
result = str.endsWith('BAR');		// false :  대소문자 구분
result = str.endsWith('foo');		// false :  'foo'로 시작하지 않음
result = str.endsWith('hoho');		// false :  'hoho'는 없음
result = str.endsWith('foo', 3);	// true :  앞에서 3개의 문자(2 index)부터 시작해서 뒤에서 앞으로 찾는다.
result = str.endsWith('123', 7);	// true :  앞에서 7개의 문자(6 index)부터 시작해서 뒤에서 앞으로 찾는다.
result = str.endsWith(123, 7);		// true :  숫자도 문자로 동일하게 처리함.

endsWith() 함수는 문자열이 특정 문자열로 끝나는지 여부를 true, false로 return해 줍니다. 대소문자를 구분하며, 시작 index를 지정할 수 있습니다. 또한 숫자도 문자와 동일하게 찾아줍니다.

 

감사합니다.

- 루미오 . LOOMIO -