문자열 검색용 JS 메서드
indexOf()
매서드는 문자열에서 지정된 텍스트가 처음 나타나는 인덱스(위치)를 반환한다.
JS에서 문자열의 첫 번째 문자 위치는 0
이다.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The indexOf() method returns the position of the first occurrence of a specified text:</p>
<p id="demo"></p>
<script>
let str = "Please locate where 'locate' occurs!";
document.getElementById("demo").innerHTML = str.indexOf("locate");
</script>
</body>
</html>
lastindexOf()
메서드는 문자열에서 지정된 텍스트가 마지막으로 나타나는 인덱스를 반환한다.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The lastIndexOf() method returns the position of the last occurrence of a specified text:</p>
<p id="demo"></p>
<script>
let str = "Please locate where 'locate' occurs!";
document.getElementById("demo").innerHTML = str.lastIndexOf("locate");
</script>
</body>
</html>
indexOf()
및 lastindexOf()
는 텍스트를 찾을 수 없는 경우 -1
을 반환한다.
두 방법 모두 검색의 시작 위치로 두 번째 매개변수를 허용한다.
lastindexOf()
메서드는 역방향으로(끝에서 첫문자 방향으로) 검색한다. 즉, 두 번째 매개변수가 15이면 검색은 위치 15에서 시작하여 문자열의 시작 부분으로 검색한다.
search()
메서드는 문자열에서 지정된 값을 검색하고 일치하는 위치를 반환한다.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The search() method returns the position of the first occurrence of a specified text in a string:</p>
<p id="demo"></p>
<script>
let str = "Please locate where 'locate' occurs!";
document.getElementById("demo").innerHTML = str.search("locate");
</script>
</body>
</html>
두 메서드의 차이점은 아래와 같다:
정규표현식은 이후 자세하게 배운다.
(참조 : https://www.w3schools.com/js/js_regexp.asp)
match()
메서드는 문자열에서 정규식과 일치하는 항목을 검색하고 일치 항목을 배열(Array) 객체로 반환한다.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Search</h2>
<p>Search a string for "ain":</p>
<p id="demo"></p>
<script>
let text = "The rain in SPAIN stays mainly in the plain";
document.getElementById("demo").innerHTML = text.match(/ain/g);
</script>
</body>
</html>
※정규식에 g
수정자가 포함되어 있지 않으면(전역 검색을 수행하기 위해) match()
메서드는 문자열에서 첫 번째 일치 항목만 반환한다.
string.match(regexp)
regexp | Required. The value to search for, as a regular expression. |
Returns: | An Array, containing the matches, one item for each match, or null if no match is found |
아래는 gi
수정 자를 사용하여 대소문자 구분없이 검색하는 방법이다.
includes()
메서드는 문자열에 지정된 값이 포함되어 있으면 true
를 반환한다.
string.includes(searchvalue, start)
searchvalue | Required. The string to search for |
start | Optional. Default 0. Position to start the search |
Returns: | Returns true if the string contains the value, otherwise false |
JS Version: | ES6 (2015) |
두 번째 인자에서 찾기 시작하는 위치를 설정해주고, 첫 번째 인자에서 찾는 문자열을 입력한다.
startsWith()
메서드는 문자열이 지정된 값으로 시작하면 true
를 반환하고, 그렇지 않으면 false
를 반환한다.
string.startsWith(searchvalue, start)
Parameter | Description |
---|---|
searchvalue | Required. The value to search for. |
start | Optional. Default 0. The position to start the search. |
※startsWith()
메서드는 대소문자를 구분한다.
ednsWith()
메서드는 문자열이 지정된 값으로 끝나면 true
를 반환하고 그렇지 않으면 false
를 반환한다.
이해하기 어려울 수도 있는데, 아래 코드를 보면 world, 11
로 입력되었다.
11 번째 문자는 world의 d이다. 그 문자가 wordl이니 true를 반환 할 수 있다.
string.endswith(searchvalue, length)
Parameter | Description |
---|---|
searchvalue | Required. The value to search for. |
length | Optional. The length to search. |
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p>Check in the 11 first characters of a string ends with "world":</p>
<p id="demo"></p>
<p>The endsWith() method is not supported in Internet Explorer.</p>
<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.endsWith("world", 11);
</script>
</body>
</html>
※endsWith()
메서드는 대소문자를 구분한다.
다른 모든 문자열 메서드를 참고하려면 아래 주소를 참조하자
(참조 : https://www.w3schools.com/jsref/jsref_obj_string.asp)