JavaScript Tutorial.18

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

JS STRINGS

JS 문자열은 텍스트를 저장하고 조작하기 위한 것이다.
JS 문자열은 따옴표 안에 쓰여진 0개 이상의 모든 문자이다.

따옴표를 사용할 수도 있고, 쌍따옴표를 사용할 수도 있다.

따옴표를 문자열로 사용할 수도 있다. 따옴표를 사용하고 싶다면, 쌍따옴표사이에 쓰고
쌍따옴표를 사용하고 싶다면, 따옴표사이에 쓰면 된다.

String Length

length

문자열의 길이를 찾으려면 내장 길이 속성을 사용하면 된다.
내장 길이 속성 : 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 text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = text.length;
</script>

</body>
</html>

Escape Character

문자열은 따옴표 사이에 써야하기 때문에, JS 아래와 같은 문자열은 인식 할 수 없다.

문자열은 "We are the so-called"까지만 인식된다.
이문제를 피하기 위해 해결책은 백슬래시\ escape문자를 사용하는 것이다.
백슬래시\ escape문자는 특수 문자를 문자로 변환시킨다.

CodeResultDescription
\''Single quote
\""Double quote
\\ \ Backslash
  • 예) \" 이 시퀀스는 문자열에 큰 따옴표를 삽입하도록 만든다.
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>The escape sequence \" inserts a double quote in a string.</p>

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

<script>
let text = "We are the so-called \"Vikings\" from the north.";
document.getElementById("demo").innerHTML = text; 
</script>

</body>
</html>

  • 예) \' 이 시퀀스는 문자열에 따옴표를 삽입하도록 만든다.
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>The escape sequence \' inserts a single quote in a string.</p>

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

<script>
let text = 'It\'s alright.';
document.getElementById("demo").innerHTML = text; 
</script>

</body>
</html>

  • 예) \\ 이 시퀀스는 문자열에 따옴표를 삽입하도록 만든다.
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>The escape sequence \\ inserts a backslash in a string.</p>

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

<script>
let text = "The character \\ is called backslash.";
document.getElementById("demo").innerHTML = text; 
</script>

</body>
</html>

아래 표는 JS에서 사용 가능한 6가지 다른 탈출(escape) 시퀀스다.

CodeResult
\bBackspace
\fForm Feed
\nNew Line
\rCarriage Return
\tHorizontal Tabulator
\vVertical Tabulator

※ 위의 6개 탈출문자는 원래 typewriters, teletypes, fax machines를 제어하기 위해 설계된 것이다.
※HTML에서는 의미가없다.

Breaking Long Code Lines

코드 라인을 쪼개는 법

문자열 전체를 내린다.

가독성을 위해 보통 한 줄당 80자 이하로 코드를 짠다.
JS문에 한 줄에 맞지 않는 경우 가장 좋은 위치는 연산자 뒤에 오는 것이다.

문자열 중간을 쪼개 내린다.

  1. \ 사용
    만약 개발자가 문자열 중간에서 줄바꿈을 하고 싶다면!
    backslash \를 사용하면 된다.

※문자열을 두줄로 쪼개는 방법(\사용방법)은 좋은 방법이 아니다.
일부 부라우저에서는 \뒤에 빈칸(빈공간)을 허용하지 않기도 한다.

  1. + 사용

단 문자열 전체를 내릴 때, \는 사용 불가

JavaScript Strings as Objects

문자열 생성과 문자열 객체 생성

일반적으로, JS 문자열은 리터럴(literals)에서 생성된 기본 값이다.

let x = "John"

그러나, 객체처럼 new키워드를 사용하여 선언할 수도 있다.
즉, 문자열 객체이다.

let y = new String("John")

※ 문자열 객체를 생성하면 안된다.
new키워드는 코드를 복잡하게 만들고, 실행속도를 늦춘다.
또한 예기치 않은 결과를 생성할 수도 있다.

문자열과 문자열 객체의 차이(==,===차이에 주목)

==,===두 연산자를 사용하여 문자열과, 문자열 객체를 비교하면
true, false로 반환된다.

<!DOCTYPE html>
<html>
<body>

<h2>Never Create Strings as Objects</h2>
<p>Strings and objects cannot be safely compared.</p>

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

<script>
let x = "John";        // x is a string
let y = new String("John");  // y is an object
document.getElementById("demo").innerHTML = (x==y);
</script>

</body>
</html>

<!DOCTYPE html>
<html>
<body>

<h2>Never Create Strings as Objects</h2>
<p>Strings and objects cannot be safely compared.</p>

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

<script>
let x = "John";        // x is a string
let y = new String("John");  // y is an object
document.getElementById("demo").innerHTML = (x===y);
</script>

</body>
</html>

문자열 객체끼리 ==,===를 비교하면 어떻게 될까
결과는 모두 false다.
JS 객체는 비교할 때마다 false가 된다.

Complete String Reference

전체 JS 문자열은 아래 주소를 참조하자.
참조에는 모든 문자열 속성 및 메소드에 대한 설명과 예시가 포함되어있다.
(참조 : https://www.w3schools.com/jsref/jsref_obj_string.asp)

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

0개의 댓글