JS String

Updated:

JavaScript Strings

JavaScript 문자열은 텍스트를 저장하고 조작하는 데 사용됩니다.

1. JavaScript Strings

자바 스크립트 문자열은 ”“(따옴표) 안에 기록 된 0 개 이상의 문자입니다.

var x = "John Doe"

//작은 따옴표나 큰 따옴표를 사용할 수 있습니다.
var carName1 = "Volvo XC60";  // Double quotes
var carName2 = 'Volvo XC60';  // Single quotes 

//인용 부호가 일치하지 않는 한 문자열안에 따옴표를 사용 할 수 있습니다.
var answer1 = "It's alright";               //It`s alright
var answer2 = "He is called 'Johnny'";      //He is called 'Johnny'
var answer3 = 'He is called "Johnny"';      //He is called "Johnny"

2. String Length(문자열 길이)

문자열 길이를 찾으려면 length속성을 이용

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;   //26

3. Escape Character(이스케이프 문자)

문자열은 따옴표 내에 작성해야하기 때문에, 자바스크립트는 이 문자열을 오해합니다.

var x = "We are the so-called "Vikings" from the north.";   //Uncaught SyntaxError:Unexpected identifier

이 문제를 방지하기위해서 백 슬래시 이스케이프 문자를 사용하면 됩니다. 백 슬래시 이스케이프 문자는 문자열의 문자의 특수문자가 지워집니다.

Code Result Description
' Single quote
" Double quote
\\ \ Backslash
// 순서는 **\"** 문자열에 큰 따옴표를 삽입합니다.
var x = "We are the so-called \"Vikings\" from the north.";

// 순서는 \'  문자열에 따옴표를 삽입합니다.
var y = 'It\`s alright.';

// 순서는 \\ 문자열에서 백슬래시를 삽입합니다.
var z = "The Character \\ is called backslash.";

여섯개의 다른 이스케이프 시퀀스는 자바스크립트에서 유효합니다.

Code Result
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tabulator
\v Vertical Tabulator

6개의 이스케이프 문자는 HTML에선 읽히지않습니다

4. Breaking Long Code Lines (최적의 코드선)

최적의 가독성을 위해 프로그래머는 80 자 보다 긴 코드라인을 방지 할 수 있습니다.

document.getElementById("demo").innerHTML = 
"Hello Dolly!";

//또한 단일 백슬러시를 사용하여 텍스트 문자열 내에서 코드라인을 분리 할 수 있습니다.
document.getElementById("demo1").innerHTML = "Hello \
Dolly!";

// 하지만 \ 방법은 바람직한 방법이 아닙니다. 보편적으로 지원을 하지 않을수 있기 때문에.

// 문자열을 깰 더 안전한 방법은 문자열 추가를 사용하는 것입니다.
document.getElementById("demo").innerHTML = "Hello " +
"Dolly!";

// 그리고 백 슬래시 코드 라인을 분리 할 수 ​​없습니다
document.getElementById("demo").innerHTML = \
"Hello Dolly!";
//You cannot break a code line with a \ backslash.

5. Strings Can be Objects

일반적으로, 자바 스크립트 문자열 리터럴에서 생성된 원시 값은 다음과 같습니다

var firstName = “John”;

그러나 문자열은 키워드와 객체로 정의 할 수 있습니다 new

var firstName = new String(“John”);

var x = "John";
var y = new String("John");

// typeof x will return string
// typeof y will return object

단 객체로 문자열을 만들면 실행속도가 느려지고 코드를 복잡하게합니다. 그래서 되도록이면 안만드는게 좋다고합니다.

==연산자 사용시에 동일하게나옴

var x = "John";
var y = new String("John");

//(x == y) is true because x and y have equal values

===연산자 사용시에는 false를 리턴

  • == 연산자 : 타입과 상관없이 비교
  • === 연산자 : 타입까지 비교
var x = "John";             
var y = new String("John");

// (x === y) is false because x and y have different types (string and object)

또한 오브젝트끼리는 비교할수 없습니다.

var x = new String("John");             
var y = new String("John");

// (x == y) is false because x and y are different objects

var x1 = new String("John");             
var y1 = new String("John");

// (x1 === y1) is false because x and y are different objects

Tags:

Categories:

Updated:

Leave a comment