Programming/JavaScript

String 객체 살펴보기

junnnhhh 2024. 3. 1. 20:22
728x90

String은 다들 알다시피 문자열을 나타내는 객체이다.

JavaScript에서 사용하는 String의 주요 내장 메서드는 무엇이 있는지 살펴보자.

 

 

String - JavaScript | MDN

The String object is used to represent and manipulate a sequence of characters.

developer.mozilla.org

 

공식 문서에 나와있는 주요 메서드는 String의 길이를 반환하는 length, String 객체에 뒤에 추가로 붙여주는 +, += 연산자, 부분 문자열 포함 여부 및 그 위치를 알려주는 indexOf(), 부분 문자열을 추출해주는 substring()이 있다.

 

String 인스턴스 생성 방법

const string1 = "A string primitive";
const string2 = 'Also a string primitive';
const string3 = `Yet another string primitive`;

const string4 = new String("A String object");

String을 선언할 때, 백틱(`) 또는 싱글 및 더블 쿼테이션을 사용하여 선언할 수 있다. ( ' ,  " )

문자열의 문자 접근 방법

"cat".charAt(1); // gives value "a"

"cat"[1]; // gives value "a"

charAt() 또는 배열 요소를 참조하는 것처럼 대괄호를 활용하여 문자를 접근할 수 있.

이 때, 위치는 1로 시작하는 것이 아닌 0으로 시작하는 것이니 주의하자.

문자열 비교 방법

const a = "a";
const b = "b";
if (a < b) {
  // true
  console.log(`${a} is less than ${b}`);
} else if (a > b) {
  console.log(`${a} is greater than ${b}`);
} else {
  console.log(`${a} and ${b} are equal.`);
}

일반 대소 비교 연산자( ==, <, >, >=, <=)를 사용하면 된다.

또 영문자의 경우, toUpperCase(), toLowerCase()를 활용하여 대문자 및 소문자로 변경할 수 있다.

var str1 = "touppercase";
var str2 = "TOLOWERCASE";

str1.toUpperCase();
// TOUPPERCASE
str2.toLowerCase();
// tolowercase

String primitives and String Object

const strPrim = "foo"; // A literal is a string primitive
const strPrim2 = String(1); // Coerced into the string primitive "1"
const strPrim3 = String(true); // Coerced into the string primitive "true"
const strObj = new String(strPrim); // String with new returns a string wrapper object.

console.log(typeof strPrim); // "string"
console.log(typeof strPrim2); // "string"
console.log(typeof strPrim3); // "string"
console.log(typeof strObj); // "object"

new를 이용해 String을 생성할 경우 object 타입을 가지게 되고,

new 연산자 없이 String을 생성하면, primitive 타입으로 취급이 되어 string으로 나오게 된다.

728x90