JavaScript Tutorial.20

ansunny1170·2021년 12월 10일
0
post-thumbnail

JS STRING SEARCH

문자열 검색용 JS 메서드

  • String indexOf()
  • String lastIndexOf()
  • String startsWith()
  • String endsWith()

String indexOf()

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>

String lastindexOf()

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>

indexOf()와 search()는 동일한가?

두 메서드의 차이점은 아래와 같다:

  • search() 메서드는 두 번째 시작 위치 인수를 사용할 수 없다.
  • indexOf() 메서드는 강력한 검색 값(정규 표현식)을 사용할 수 없다.

    정규표현식은 이후 자세하게 배운다.
    (참조 : https://www.w3schools.com/js/js_regexp.asp)

String match()

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() 메서드는 문자열에서 첫 번째 일치 항목만 반환한다.

match() Syntax

string.match(regexp)

regexpRequired. 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수정 자를 사용하여 대소문자 구분없이 검색하는 방법이다.

String includes()

includes()메서드는 문자열에 지정된 값이 포함되어 있으면 true를 반환한다.

includes() Syntax

string.includes(searchvalue, start)

searchvalueRequired. The string to search for
startOptional. Default 0. Position to start the search
Returns:Returns true if the string contains the value, otherwise false
JS Version:ES6 (2015)

두 번째 인자에서 찾기 시작하는 위치를 설정해주고, 첫 번째 인자에서 찾는 문자열을 입력한다.

Browser Support

String startsWith()

startsWith() 메서드는 문자열이 지정된 값으로 시작하면 true를 반환하고, 그렇지 않으면 false를 반환한다.

startsWith() Syntax

string.startsWith(searchvalue, start)

ParameterDescription
searchvalueRequired. The value to search for.
startOptional. Default 0. The position to start the search.

startsWith() 메서드는 대소문자를 구분한다.

Browser Support

String endsWith()

ednsWith() 메서드는 문자열이 지정된 값으로 끝나면 true를 반환하고 그렇지 않으면 false를 반환한다.

endsWith() Syntax

이해하기 어려울 수도 있는데, 아래 코드를 보면 world, 11로 입력되었다.
11 번째 문자는 world의 d이다. 그 문자가 wordl이니 true를 반환 할 수 있다.

string.endswith(searchvalue, length)

ParameterDescription
searchvalueRequired. The value to search for.
lengthOptional. 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() 메서드는 대소문자를 구분한다.

Browser support

Complete string reference

다른 모든 문자열 메서드를 참고하려면 아래 주소를 참조하자
(참조 : https://www.w3schools.com/jsref/jsref_obj_string.asp)

profile
공정 설비 개발/연구원에서 웹 서비스 개발자로 경력 이전하였습니다. Node.js 백엔드 기반 풀스택 개발자를 목표로 하고 있습니다.

0개의 댓글