상세 컨텐츠

본문 제목

javascript 문자열 검색/ 문자열 찾기 indexOf() 함수 substr_count() 함수

IT공부방/jQuery, ajax, java

by 동해둘리 2017. 1. 2. 21:59

본문

반응형




1. 처음으로 발견되는 문자열 위치 찾는 함수 indexOf()



javascript 코딩시에, 특정 문자열에서 원하는 문자/문자열을 찾을 때 

사용하는 함수로 indexOf() 함수를 사용합니다.


array.indexOf(item, start)


ParameterDescription
itemRequired. The item to search for
startOptional. Where to start the search. Negative values will start at the given position counting from the end, and search to the end.



var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");



위와 같이 코딩햇을 경우, n 의 값은  13 이 나오게 됩니다.

welcome 이라는 문자열이 13번째 위치에서 발견되기 때문입니다.



만약, 문자열이 발견되지 않을 경우에는 -1 이 결과값으로 나오게 됩니다.



var str = "Hello world, welcome to the universe. welcome welcome";

var n = str.indexOf("welcome");


위와 같이, welcome 이 여러개가 발견되더라도

처음 발견되는 위치인 13 이 결과값으로 리턴되게 됩니다.



2. 찾는 문자열이 몇개 발견되는 지 확인하는 함수 substr_count() 함수



substr_count(string,substring,start,length)


ParameterDescription
stringRequired. Specifies the string to check
substringRequired. Specifies the string to search for
startOptional. Specifies where in string to start searching
lengthOptional. Specifies the length of the search



<?php
echo substr_count("Hello world. The world is nice","world");
?>


위와 같이 코딩하여 실행해보면, world 라는 문자열이 총 2번 발견되기 때문에

결과값은 2가 출력되게 됩니다.


반응형

관련글 더보기

댓글 영역