퍼블리싱/html css js

[Javascript] includes() / startsWith() / endsWith()

임고미 2020. 9. 25. 10:23
728x90
300x250
  includes() startsWith()  endsWith()
그 단어 를 포함하고 있니? 로 시작하니? 로 끝나니?
사용가능한 범위 arr, string string string

================================================

includes( ) - Array

메서드는 배열이 특정 요소를 포함하고 있는지 판별합니다.

반환값 : Boolean ( true || false )

arr.includes(valueFind[, formIndex])

valueFind : 탐색할 요소 < 참고 > 문자나 문자열을 비교할 때, 대소문자를 구분합니다.
formIndex :  이 배열에서 searchElement 검색을 시작할 위치입니다.
                 음의 값은 array.length + fromIndex의 인덱스를 asc로 검색합니다. 기본값은 0입니다

예제 

[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(3, 3);  // false 
[1, 2, 3].includes(3, -1); // true 

[1,  2,  3] => 배열
 0  1   2  => index 번호

array.length + fromIndex 을 생각해본다면,

2번째 줄 코드에선, 3 + 3 한곳부터 숫자 3 을검색할 것입니다.

3번째 줄 코드에선 3 + ( - 1 ) 일테니, 3은 존재합니다.

 

따라서,

fromIndex 가 배열의 길이보다 같거나 크다면, false 를 반환합니다.

 

충격

그런데 사용해야한다면,

침착하게 폴리필을 위에 적어주면 됩니다.

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      // 1. Let O be ? ToObject(this value).
      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      function sameValueZero(x, y) {
        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
      }

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        if (sameValueZero(o[k], searchElement)) {
          return true;
        }
        // c. Increase k by 1. 
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

 

includes( ) - String

하나의 문자열이 다른 문자열에 포함되어 있는지를 판별합니다.
includes() 메서드는 대소문자를 구별합니다.

반환값 : Boolean ( true || false )

string.includes(searchString[, position])

searchString: 이 문자열에서 찾을 다른 문자열.
position : searchString을 찾기 시작할 위치. 기본값 0.

includes() 메서드는 대소문자를 구별합니다.

var str = 'To be, or not to be, that is the question.';

console.log(str.includes('To be'));       // true
console.log(str.includes('question'));    // true
console.log(str.includes('nonexistent')); // false
console.log(str.includes('To be', 1));    // false
console.log(str.includes('TO BE'));       // false

ie에서는 사용이 불가하므로, 사용하는 함수 위에 폴리필을 적어줍니다.

if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';
    if (typeof start !== 'number') {
      start = 0;
    }
    
    if (start + search.length > this.length) {
      return false;
    } else {
      return this.indexOf(search, start) !== -1;
    }
  };
}

- 위의 Array에서와 사용방법이 비슷하나, option부분이 다른걸 확인해줍니다!

startsWith()

메서드는 배열이 문자열이 특정 문자열로 시작하는지 확인하는 메서드입니다.
IE는 Edge부터 지원합니다. 그러나 우리에겐 폴리필이 존재합니다. 하단 확인

반환값 : Boolean ( true || false )

str.startsWidth(searchString[, position])
searchString : 문자열의 시작 지점에서 탐색할 문자열
position : searchString을 탐색할 위치. 기본값 0.

//startswith
var str = 'To be, or not to be, that is the question.';

console.log(str.startsWith('To be'));         // true
console.log(str.startsWith('not to be'));     // false
console.log(str.startsWith('not to be', 10)); // true

position값은, 띄어쓰기를 포함합니다.
6번째 줄을 참고해보세요!

if (!String.prototype.startsWith) {
	String.prototype.startsWith = function(search, pos) {
		return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
	};
}

 

endsWith()

메서드를 사용하여 어떤 문자열에서 특정 문자열로 끝나는지를 확인하는 메서드입니다.

반환값 : Boolean ( true || false )


searchString : 이 문자열의 끝이 특정 문자열로 끝나는지를 찾기 원하는 문자열입니다.
length : 찾고자 하는 문자열의 길이값이며, 기본값은 문자열 전체 길이입니다.
           문자열의 길이값은 문자열 전체 길이 안에서만 존재하여야 합니다.

예제

var str = 'To be, or not to be, that is the question.';

console.log(str.endsWith('question.')); // true
console.log(str.endsWith('to be'));     // false
console.log(str.endsWith('to be', 19)); // true

마찬가지로, ie 에선 작동하지 않으니

폴리필을 적어줍니다.

if (!String.prototype.endsWith) {
  String.prototype.endsWith = function(searchString, position) {
      var subjectString = this.toString();
      if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
        position = subjectString.length;
      }
      position -= searchString.length;
      var lastIndex = subjectString.indexOf(searchString, position);
      return lastIndex !== -1 && lastIndex === position;
  };
}

참고 developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

728x90
300x250