문서의 이전 판입니다!
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; // Banana </script> </body> </html>
기억하세요 : 자바 스크립트는 0부터 위치를 계산합니다. 첫 번째 위치는 0입니다.
매개 변수가 음수이면, 위치는 문자열의 끝부터 계산됩니다.
다음 예제는 -12 위치에서 -6 위치까지 문자열의 일부를 잘라냅니다.
<script> let str = "Apple, Banana, Kiwi"; let res = str.slice(-12, -6); document.getElementById("demo").innerHTML = res; console.log(str.length); </script>
str.slice(beginImdex[, endIndex])
beginIndex: - 입력값이 추출 시작점이 되는 인덱스 - 음수인 경우, beginIndex = str.length(문자열 길이) + beginIndex - 에제) beginIndex = -3 인 경우, 시작점은 strLength + (-3) endIndex: - 0부터 시작하는 추출 종료점 인덱스로 그 직전까지 추출 - endIndex 위치의 문자는 추출에 포함되지 않습니다.
두 번째 매개변수가 없는 경우, 메서드는 해당 문자열의 나머지 부분을 잘라냅니다.
(–> 입력된 매개변수가 나타내는 인텍스 번호의 지점부터 인덱스 마지막 번호까지의 문자열을 잘라냅니다)
<script> let str = "Apple, Banana, Kiwi"; let res = str.slice(7); document.getElementById("demo").innerHTML = res; // Banana, Kiwi </script>
두 번째 매개변수가 없으면서, 첫 번째 매개변수가 음수인 경우는 마지막 인텍스에서부터 계산합니다.
<script> let str = "Apple, Banana, Kiwi"; let res = str.slice(-12); document.getElementById("demo").innerHTML = res; // Banana, Kiwi </script>
Internet Explorer 8 및 이전 버전에서는 음수 위치가 작동하지 않습니다.
substring()
은 slice()
와 유사합니다.
차이점은 substring()
은 음수 인덱스를 허용 할 수 없다는 것입니다.
<script> let str = "Apple, Banana, Kiwi"; let res = str.substring(7, 13); // index7부터 12까지 추출 document.getElementById("demo").innerHTML = res; // Banana </script>
두 번째 매개변수를 생략하면 substring()
은 나머지 문자열을 잘라냅니다.
substr()
은 slice();;와 유사합니다.
substr()
차이점은 두 번째 매개변수가 추출될 부분의 길이를 지정한다는 것입니다.
<code javascript>
<script>
let str = “Apple, Banana, Kiwi”;
let res = str.substr(7, 10); index7부터 10개에 해당하는 문자를 추출
document.getElementById(“demo”).innerHTML = res; Banana, Ki
</script>
</code>
두 번째 매개변수를 생략하면, 은 나머지 문자열을 잘라냅니다.
replace()
<code javascript>
<script>
let str = “Apple, Banana, Kiwi”;
let res = str.substr(8); index7부터 끝까지의 문자을 추출
document.getElementById(“demo”).innerHTML = res; anana, Kiwi
</script>
</code>
첫 번째 매개 변수가 음수이면 위치는 문자열 끝부터 계산된 인덱스 지점부터 오른쪽으로 나머지를 추출합니다.
<code javascript>
<script>
let str = “Apple, Banana, Kiwi”;
let res = str.substr(-8); index-8부터 끝까지의 문자을 추출
document.getElementById(“demo”).innerHTML = res; na, Kiwi
</script>
</code>
=====Replacing String Content=====
메서드는 문자열에서 지정된 값을 다른 값으로 대체(교환)합니다.
replace()
<code javascript>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>Replace “Microsoft” with “W3Schools” in the paragraph below:</p>
<button onclick=“myFunction()”>Try it</button>
<p id=“demo”>Please visit Microsoft!</p>
<script>
function myFunction() {
let str = document.getElementById(“demo”).innerHTML;
let txt = str.replace(“Microsoft”, “W3Schools”);
document.getElementById(“demo”).innerHTML = txt;
}
</script>
</body>
</html>
</code>
메서드는 호출되는 문자열을 변경하지 않습니다. 새 문자열을 반환합니다.
replace()'' 메서드는 첫 번째 일치 항목만 교환합니다.
기본적으로,
<!DOCTYPE html> <html> <body> <h2>JavaScript String Methods</h2> <p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p> <button onclick="myFunction()">Try it</button> <p id="demo">Please visit Microsoft and Microsoft!</p> <script> function myFunction() { let str = document.getElementById("demo").innerHTML; let txt = str.replace("Microsoft", "W3Schools"); document.getElementById("demo").innerHTML = txt; } </script> </body> </html>