JavaScript Tutorial.19

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

JS STRING METHODS

John Doe와 같은 기본 값은 속성(property)이나 메서드를 가질 수 없다.(객체가 아니기 때문에)
그러나, JS에서는 메서드와 속성을 실행할 때 JS가 기본 값을 객체로 취급하기 때문에 메서드와 속성을 기본 값에도 사용할 수 있다.

String Length

length속성은 문자열의 길이를 반환한다.

Extracting String Parts

문자열 중 일부를 추출 하는 메서드 3가지
1. slice(start, end)
2. substraing(start, end)
3. substr(start, length)

The String slice() Method

기본 사용방법

<!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="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>


<script>
let str = "Apple, Banana, Kiwi";
let str1 = "p 부터 k까지 출력"
document.getElementById("demo1").innerHTML = str; 
document.getElementById("demo2").innerHTML = str1; 
document.getElementById("demo3").innerHTML = str.slice(1,13); 
</script>

</body>
</html>

  • JS에서 문자열 첫번째는 0이다.

slice(x,y)에 음수 입력시

음수를 인자로 입력시 문자열의 맨 끝에서 부터 계산한다.

slice(x) 양수 한가지만 입력시

<!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";
document.getElementById("demo").innerHTML = str.slice(7);
</script>

</body>
</html>


7번째 부터 끝까지 출력한다. y인자 입력안하면 default로 끝으로 설정됨을 알 수 있다.

slice(x) 음수 한가지만 입력시

맨 끝에서부터 계산한 곳부터 끝까지 출력한다.

<!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";
document.getElementById("demo").innerHTML = str.slice(-12);
</script>

</body>
</html>

The String substring() Method

substring()slice()와 비슷하다.
다른점은 substring()은 음수를 입력 할 수 없다는 것.
역시 substring(x,y) 중에 x만 입력하고 y를 누락시키면
동일하게 맨 끝까지 출력한다.

The String substr() Method

substr()slice()와 비슷하다.


역시 substr(x,y) 중에 x만 입력하고 y를 누락시키면
동일하게 맨 끝까지 출력한다.

음수를 입력하면 맨 끝에서 부터 세면서 출력한다.

Replacing String Content

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!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML;
  document.getElementById("demo").innerHTML =
  text.replace("Microsoft","W3Schools");
}
</script>

</body>
</html>


replace()메서드는 호출한 문자열을 변경하는 것이 아닌, 새 문자열을 반환하는 것이다.

  • 기본적으로 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 text = document.getElementById("demo").innerHTML; 
  document.getElementById("demo").innerHTML =
  text.replace("Microsoft","W3Schools");
}
</script>

</body>
</html>


  • 기본적으로 replace()메서드는 대소문자를 구분한다.
  • 대소문자를 구분하지 않으려면 /i플래그(비구분) 구문과 함께 정규식을 사용하면된다.

    /i플래그가 사용된 정규식은 ''따옴표 없이 사용한다.

모든 일치 항목을 바꾸려면 /g 플래그(전역 일치) 와 함께 정규식을 사용한다.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String Methods</h2>

<p>Replace all occurrences of "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 text = document.getElementById("demo").innerHTML; 
  document.getElementById("demo").innerHTML =
  text.replace(/Microsoft/g,"W3Schools");
}
</script>

</body>
</html>


JS Regular expressions(정규식) 장에서 정규식에 대해 더 많이 배울 수 있다.
(참조 : https://www.w3schools.com/js/js_regexp.asp)

Converting to Upper and Lower Case

  • 대문자 변환기
    toUpperCase()를 사용하여 소문자를 대문자로 변경가능하다.
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String Methods</h2>
<p>Convert string to upper case:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Hello World!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML;
  document.getElementById("demo").innerHTML =
  text.toUpperCase();
}
</script>

</body>
</html>


  • 소문자 변환기
    toLowerCase()를 사용하여 대문자를 소문자로 변경가능하다.

The String concat() Method

concat() 두개 혹은 그 이상의 문자열을 이어 붙인다.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String Methods</h2>

<p>The concat() method joins two or more strings:</p>

<p id="demo"></p>

<script>
let text1 = "Hello";
let text2 = "World!";
let text3 = text1.concat(" ",text2);
document.getElementById("demo").innerHTML = text3;
</script>

</body>
</html>

  • concat()메서드는 +연산자대신 사용 된다. 아래 두 줄은 동일하다.

    ※모든 문자열 메서드는 새 문자열을 반환한다. 그것들은 원본의 문자열을 수정하지 않는다.
    공식적으로 : 문자열은 변경할 수 없다. 문자열은 변경할 수 없고 교체만 가능하다.

String.trim()

trim() 매서드는 문자열의 앞뒤에 존재하는 빈공간을 삭제한다.

JavaScript String Padding

ECMAScript2017은 문자열의 시작과 끝에 패딩을 지원하기 위해 두개의 String 메서드인 padStart 및 padEnd를 추가하였다.

  • String.padStart(x,y)
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String Methods</h2>

<p>The padStart() method pads a string with another string:</p>

<p id="demo"></p>

<script>
let text = "5";
document.getElementById("demo").innerHTML = text.padStart(4,0);
</script>

</body>
</html>

  • String.padEnd(x,y)

문자열 패딩 지원 브라우저

문자열 패딩은 internet Explorer에서 지원되지 않는다.

Extracting(추출) String Characters

문자열 문자를 추출하는 3가지 방법 :

  • charAt(position)
  • charCodeAt(position)
  • Property access []

The String charAt() Method

charAt() 메서드는 문자열의 지정된 인덱스(위치)에 있는 문자를 반환한다.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String Methods</h2>

<p>The charAt() method returns the character at a given position in a string:</p>

<p id="demo"></p>

<script>
var text = "HELLO WORLD";
document.getElementById("demo").innerHTML = text.charAt(0);
</script>

</body>
</html>

The String charCodeAt() Method

charCodeAt()메서드는 문자열의 지정된 인덱스에 있는 문자의 유니코드를 반환한다.
해당 메서드는 UTF-16 코드를 반환한다.
UTF-16 : 0에서 65535 사이의 정수

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String Methods</h2>

<p>The charCodeAt() method returns the unicode of the character at a given position in a string:</p>

<p id="demo"></p>

<script>
let text = "HELLO WORLD";
document.getElementById("demo").innerHTML = text.charCodeAt(0);
</script>

</body>
</html>

Property Access(속성 접근)

ECMAScript 5(2009)는 문자열에 대해 배열속성의 접근을 허용한다.(속성 접근)

<html>
<body>

<h2>JavaScript String Methods</h2>

<p>ECMAScript 5 allows property access on strings:</p>

<p id="demo"></p>

<script>
var str = "HELLO WORLD";
document.getElementById("demo").innerHTML = str[0];
</script>
</body>
</html>

※property access(속성 접근)은 예측이 어렵다.
문자열을 배열처럼 보이게 하기 때문인데(실제로는 그렇지 않다.)
문자가 없으면 []undefined를 반환하고 charAt()빈 문자를 반환한다.
str[0]="A"는 오류를 표시하지 않는다.(단 작동하지 않는다!)

※만약 문자열을 배열로 사용하고 싶다면, 배열로 변환이 가능하다.

Converting a String to an Array

문자열은 split()메서드를 사용하여 배열로 변환할 수 있다.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String Methods</h2>
<p>Display the first array element, after a string split:</p>

<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>

<script>
let text = "a,b,c,d,e,f";
const myArray = text.split(",");
document.getElementById("demo").innerHTML = myArray[0];
document.getElementById("demo1").innerHTML = myArray[1];
document.getElementById("demo2").innerHTML = myArray[2];
</script>

</body>
</html>


구분 기호를 생략하면 반환된 배열에 인덱스 [0]의 전체 문자열이 포함된다.
구분 기호가 ""이면 반환된 배열은 단일 문자의 배열이 된다.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String Methods</h2>
<p>Using String.split():</p>

<p id="demo"></p>

<script>
let text = "Hello";
const myArr = text.split("");

text = "";
for (let i = 0; i < myArr.length; i++) {
  text += myArr[i] + "<br>"
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Complete String Reference

전체 문자열관련 내용을 참고하려면 아래 주소를 참조한다.
(참조 : https://www.w3schools.com/jsref/jsref_obj_string.asp)

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

0개의 댓글