문서의 이전 판입니다!
JavaScript String Methods
문자열 메서드는 문자열 작업에 도움이 됩니다.
“John Doe”와 같은 원시 값(Primitive values)은 속성이나 메서드를 가질 수 없습니다 (객체가 아니기 때문에).
그러나 JavaScript에서는 메서드와 속성을 실행할 때 원시 값을 객체로 취급하기 때문에,
JavaScript로, 메서드와 속성도 원시 값에 사용할 수 있습니다.
length
속성은 문자열의 길이를 반환합니다.
<!DOCTYPE html> <html> <body> <h2>JavaScript String Properties</h2> <p>The length property returns the length of a string</p> <p id="demo"></p> <script> let txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; let sln = txt.length; document.getElementById("demo").innerHTML = sln; </script> </body> </html>
indexOf()
메서드는 문자열에서 지정된 텍스트의 처음 나타나는 곳(occurrence)의 인덱스(위치)를 반환합니다.
<!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!"; let pos = str.indexOf("locate"); document.getElementById("demo").innerHTML = pos; // 7 </script> </body> </html>
%%JavaScript%%는 0부터 위치를 계산합니다. 0은 문자열의 첫 번째 위치, 1은 두 번째, 2는 세 번째 ...
lastIndexOf()
메서드는 문자열에서 지정된 텍스트가 마지막으로 나타나는 곳의 시작 위치(인텍스)를 반환합니다.
<!DOCTYPE html> <html> <body> <h2>JavaScript String Methods</h2> <p>The lastIndexOf() method returns the positon of the last occurrence of a specified text:</p> <p id="demo"></p> <script> let str = "Please locate where 'locate' occurs!"; let pos = str.lastIndexOf('locate'); document.getElementById("demo").innerHTML = pos; // 21 </script> </body> </html>
텍스트가 발견되지 않는 경우, indexOf()
및 lastIndexOf()
는 모두 -1을 반환합니다.
<!DOCTYPE html> <html> <body> <h2>JavaScript String Methods</h2> <p>Both indexOf() and lastIndexOf() returns -1 if the text is not found:</p> <p id="demo"></p> <script> let str = "Please locate where 'locate' occurs!"; let pos = str.indexOf("John"); document.getElementById("demo").innerHTML = pos; // -1 </script> </body> </html>
두 메서드 모두 검색의 시작 위치를 두 번째 매개 변수로 허용합니다.
<!DOCTYPE html> <html> <body> <h2>JavaScript String Methods</h2> <p>The indexOf() method accepts a second parameter as thee starting position for the search:</p> <p id="demo"></p> <script> let str = "Please locate where 'locate' occurs!"; let pos = str.indexOf("locate", 15); //index[15]부터 검색을 시작 document.getElementById("demo").innerHTML = pos; // 21 </script> </body> </html>
lastIndexOf()
메서드는 뒤로(끝에서 처음으로) 검색합니다.
즉, 두 번째 매개 변수가 15
이면, 검색은 위치 15에서 시작하고, 문자열의 시작 부분까지 검색합니다.
<!DOCTYPE html> <html> <body> <h2>JavaScript String Methods</h2> <p>The lastIndexOf() method accepts a second parameter as the stating position for the search.</p> <p>Remember that the lastIndexOf() method searches backwords, so position 15 means start the search at position 15, and search to the beginning.</p> <p>Position 15 is position 15 from the beginning</p> <p id="demo"></p> <script> let str = "Please locate where 'locate' occurs!"; let pos = str.lastIndexOf("locate", 15); document.getElementById("demo").innerHTML = pos; // 7 console.log(str.length); // 36 console.log(str[15]); // h </script> </body> </html>
Tip:lastIndexOf() 메서드는 지정된 인덱스 값에서 왼쪽(index[0]의 방향으로)으로 검색을
시작하면서 처음으로 나타나는 searchValue의 원래 인텍스 번호를 반환한다.
search()
메서드는 지정된 값에 해당하는 문자열을 검색하고, 일치하는 위치를 반환합니다.
<!DOCTYPE html> <html> <body> <h2>JavaScript String Methods</h2> <p>The search() method returns the position of the first occurrnece of a specified text in a string.</p> <p id="demo"></p> <script> let str = "Please locate where 'locate' occurs!"; let pos = str.search("locate"); document.getElementById("demo").innerHTML = pos; // 7 </script> </body> </html>
두 메서드 indexOf()
및 search()
는 동일합니까?
동일한 인수(매개 변수)를 수용하고 동일한 값을 반환합니까?
이 두 가지 메서드는 동일하지 않습니다. 차이점은 다음과 같습니다.
search()
메서드는 두 번째 시작 위치 인수를 사용할 수 없습니다.indexOf()
메서드는 강력한 검색 값 (정규식)을 사용할 수 없습니다.
이후 장에서 정규식에 대해 자세히 알아볼 것입니다.
문자열의 일부분을 추출하는 3가지 방법이 있습니다.
slice(start, end)
substring(start, end)
substr(start, length)
slice()
는 문자열의 일부를 추출하고, 추출된 부분을 새 문자열로 반환합니다.
이 메서드는 시작 위치와 끝 위치 (끝이 포함되지 않음)라는 두 가지 매개 변수를 사용합니다.
다음 예제는 위치 7에서 위치 12 (13-1)까지 문자열의 일부를 자릅니다.
<!DOCTYPE html> <html> <body> <h2>JavaScript String Methods</h2> <p>The slice() method extract a part of a string and returns the extracted parts in a new string:</p> <p id="demo"></p> <script> let str = "Apple, Banana, Kiwi"; let res = str.slice(7, 13); // 7-시작, 13-종료, 포함X document.getElementById("demo").innerHTML = res; </script> </body> </html>