영벨롭 개발 일지

[JavaScript]자바스크립트 문자열 데이터 String 객체 본문

Programming Language/JavaScript

[JavaScript]자바스크립트 문자열 데이터 String 객체

영벨롭 2022. 5. 9. 19:56

[ String 객체 생성 및 초기화 ]

 

 자바스크립트의 문자열 데이터를 생성하는 방식은 문자열 리터럴 / 템플릿 리터럴 / String 전역 개체 세 가지가 있습니다. 

 

 문자열 리터럴은 작은 따옴표(' ') 또는 큰 따옴표(" ")로 문자열을 생성합니다. 

 

 템플릿 리터럴은 벡틱 기호(` `)와 ${ }을 사용하여 변수에 저장되어 있는 문자열을 포함한 문자열을 생성합니다. 

 

 String 전역 개체를 직접적으로 사용하여 문자열을 생성할 수 있습니다. 

 

// 문자열 리터럴
const str1 = 'hello';
const str2 = "world";

// 템플릿 리터럴
const str3 = `${str1} ${str2}!`;

// String 전역 객체
const str4 = String('hello world');

 

 

 

 

 

[ 문자열의 길이 - length property ]

 

 인스턴스 property인 length를 이용하여 문자열의 길이를 알 수 있습니다. 

 

const str = "hello world";

console.log(str.length)  // 11

 

 

 

 

 

[ 문자열 원소 접근 ]

 

 문자열의 원소를 접근할 때는 배열과 같이 str[index] 로 접근하거나 str.at(index) 메소드를 이용하여 접근할 수 있습니다. 

 

 str[index]의 인덱스는 zero based 숫자로 0부터 시작하여 음이 아닌 정수가 가능하며 범위는 0~n-1 입니다. (n은 문자열의 길이)

 

 str.at(index)의 인덱스는 음이 아닌 정수 뿐만 아니라 음수도 가능하며 범위는 -n ~ n-1 입니다. 

 

 이때 인덱스 범위를 벗어난 숫자로 접근하면 undefined가 나옵니다. 

 

  • str[index]
const str = "hello world";

console.log(str[0]);  // h
console.log(str[3]);  // l
console.log(str[-1]);  // undefined
console.log(str[999]);  // undefined

 

  • str.at(index)
const str = "hello world";

console.log(str.at(0));  // h
console.log(str.at(3));  // l
console.log(str.at(-1));  // d
console.log(str.at(999));  // undefined

 

 

 

[ 기타 메소드 ]

 

  • 여러 문자열 병합 - concat()

 str1.concat(str2, ... ) 메소드는 concat 메소드를 실행한 문자열 뒤에 인수로 넘겨준 문자열을 붙여서 새로운 문자열을 반환해줍니다. 

 

 이때 기존의 문자열들의 값은 손상되지 않습니다. 

 

const str1 = "hello ";
const str2 = "new ";
const str3 = "world";

const str4 = str1.concat(str2, str3);

console.log(str1); // hello
console.log(str2); // new
console.log(str3); // world
console.log(str4); // hello new world

 

 

  • 특정 문자열이 있는지 확인 - includes()

 str.includes(str2) 는 문자열 str 내에 str2를 포함하고 있는지를 확인하는 메소드입니다. 

 

 포함되어 있다면 true를, 그렇지 않다면 false를 반환합니다. 

 

const str = "hello world";

console.log(str.includes("world"));  // true

 

 

 

  • 특정 문자열의 위치 찾기 - indexOf()

 str.indexOf(str2)는 문자열 str 내에 str2 가 있다면 그 시작 index를 반환하고, 없다면 -1을 반환합니다. 

 

const str = "hello world";

console.log(str.indexOf("world"));  // 6
console.log(str.indexOf("new"));    // -1

 

 

 

  • 문자열 길이를 확인하고 문자열 추가 - padStart(), padEnd()

 str.padStart(size, str2) 는 str의 길이가 size보다 작다면 size 길이가 될 때까지 str2를 문자열 앞 부분에 추가하여 새로운 문자열을 반환해주는 메소드 입니다. 

 

 padEnd()는 반대로 문자열 끝에 추가하는 메소드입니다. 

 

 이때 기존 문자열의 내용은 손상되지 않습니다. 

 

const a = '1';
const b = '12';

const new_a = a.padStart(2, '0');
const new_b = b.padStart(2, '0');

console.log(a);      // 1
console.log(new_a);  // 01
console.log(b);      // 12
console.log(new_b);  // 12

 

 

 

 

  • 문자열 슬라이싱 - slice()

 str.slice(a, b) 는 index a부터 b-1 번째까지의 문자열을 반환해줍니다. 

 

 이때 기존 문자열은 손상되지 않습니다. 

 

const str1 = "hello world";
const str2 = str1.slice(0, 5);

console.log(str1); // hello world
console.log(str2); // hello

 

 

 

  • 문자열 대체 - replace()

 str.replace(str2, str3)는 문자열 str 내부에 있는 str2 문자열을 str3으로 교체해주어 새로운 문자열을 반환해주는 메소드입니다. 

 

 이때 기존 문자열은 손상되지 않습니다. 

 

 만약 str2가 str에 없는 문자열이라면 아무것도 교체되지 않은 원본 문자열이 반환됩니다. 

 

const str1 = "hello world";
const str2 = str1.replace('world', 'newWorld');
const str3 = str1.replace('new', 'Hi');
const str4 = str1.replace(' ', ' Big ');

console.log(str1);  // hello world
console.log(str2);  // hello newWorld
console.log(str3);  // hello world
console.log(str4);  // hello Big world

 

 

 

  • 문자열 앞/뒤 공백 제거 - trim()

 str.trim()은 str 의 앞 뒤 공백을 제거해주어 새로운 문자열을 반환해주는 메소드입니다. 

 

 이때 앞 공백만 지우고 싶다면 trimStart()를 뒤 공백만 지우고 싶다면 trimEnd()를 사용합니다. 

 

 이때 기존 문자열의 내용은 손상되지 않습니다. 

 

const str1 = "     Hello World  ";
const str2 = str1.trim();
const str3 = str1.trimStart();
const str4 = str1.trimEnd();

console.log(str1); //     Hello World  
console.log(str2); //Hello World
console.log(str3); //Hello World
console.log(str4); //     Hello World
반응형