Study/JavaScript
[JS] contains & indexOf
taecongs
2023. 7. 26. 15:53

알고있으면 좋은 Javascript Tip✨
contains()
- 특정 문자 포함 여부를 알 수 있다.
export default function isPoiAlarmCount(){
let $iconList = document.querySelectorAll('.icon');
$iconList.forEach((data) => {
data.addEventListener('click', async (e) => {
if(document.querySelector("#poi-container") && data.classList.contains('active')){
return;
}
}
- 문서(DOM) 안에서 #poi-container라는 ID를 가진 요소를 찾는다.
- data라는 변수에서 active라는 클래스가 있는지 확인한다.
- 두 조건이 모두 참일 경우 아무 작업도 하지 않고 함수가 종료된다.
- 그렇지 않은 경우 함수는 정상적으로 실행된다.
indexOf()
- 특정 문자열을 찾고 그 문자열이 첫번째로 나타나는 위치(index)를 리턴한다.
- 찾는 문자열이 없는 경우에는 -1을 리턴한다.
- 문자열을 찾을때는 대소문자를 구분해야한다.
let str = "Hi guys. Nice to meet you.";
str.includes("to"); // true
str.indexOf("to"); // 14
str.indexOf("man"); // -1
if (str.indexOf("Bye") > -1) {
alert("Bye 포함");
}