JavaScript

[Javascript] 배열, 문자열에 특정 값 포함 여부 확인하기, 특정 값 위치 찾기 / includes(), indexOf()

hellosonic 2023. 8. 2. 18:31

array.includes(value) : 배열, 문자열에 특정 값 포함 여부 확인하기 

var string = "I want to earn money a lot";
var arr = [1,2,3]

console.log(arr.includes(1)); //true
console.log(arr.includes(4)); //false

console.log(string.includes("c")); //false
console.log(string.includes("a")); //true

string.indexOf(searchvalue, position) : 배열, 문자열에 특정 값 위치 찾기

  • searchvalue : 찾을 문자열
  • position(optional) : 기본 값은 0. string에서 searchvalue를 찾기 시작할 위치
  • 찾는 문자열이 없으면 -1을 리턴
  • 문자열을 찾을 때 대소문자를 구분
var string = "abab";

console.log(string.indexOf("ab")); //0
console.log(string.indexOf("ba")); //1
console.log(string.indexOf("abc")); //-1
console.log(string.indexOf("AB")); //-1

console.log(string.indexOf("ab",1)); //2

모든 특정 값 위치 찾기 : 간단한 프로그래밍을 활용하여 구할 수 있다.

var string = "abcabcabc";
var searchvalue = "ab";

var pos = 0;

while (true) {
    var foundPos = string.indexOf(searchvalue, pos);
    if (foundPos == -1) break;
    
    console.log(foundPos); //0 3 6
    pos = foundPos + 1;
}