Javascript

특정 문자 위치 찾기 - indexOf 함수

minsun309 2024. 8. 25. 13:02

자바스크립트에서 특정 문자 위치 찾는 방법

indexOf()

  • 배열, 문자열에서 주어진 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고, 찾을 수 없는 경우 -1을 반환하며 문자열을 찾을 때 대소문자를 구분한다.

문법 : indexOf(searchElement, fromIndex) ( fromIndex는 optional한 값 )

const string = "abad";

console.log(string.indexOf('a')); // 0

const drink = ['milk', 'beer', 'coffee', 'jucie'];

console.log(drink.indexOf('coffee')); // 2
console.log(drink.indexOf('water'));  // -1
console.log(drink.indexOf('WATER'));  // -1

 

fromIndex 값을 넣으면 해당 인덱스부터 검색한다. fromIndex가 생략되면, 0이 사용되어 전체 배열이 검색

const string = "abad";

console.log(string.indexOf('a', 1)); // 2

 

search()

  • 일치 항목에 대한 검색을 실행하여 첫 번째 일치 항목의 인덱스를 반환한다.
  • 찾고자 하는 문자열이 존재하지 않는 경우 -1을 리턴 한다.

문법 : search(regexp)

const string = "apple";

console.log(string.search('pl')) // 2
console.log(string.search('z')) // -1

 

 

참고

 

Array.prototype.indexOf() - JavaScript | MDN

Array 인스턴스의 indexOf() 메서드는 배열에서 주어진 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고, 찾을 수 없는 경우 -1을 반환합니다.

developer.mozilla.org

 

 

String.prototype.search() - JavaScript | MDN

The search() method of String values executes a search for a match between a regular expression and this string, returning the index of the first match in the string.

developer.mozilla.org