본문 바로가기

코딩/Javascript

자바스크립트 - 문자열 합치기 (concat() 함수)

반응형

concat() 함수는 배열문자열에 사용이 가능하다.

이번 포스팅에선 문자열에 concat() 함수가 어떻게 사용 가능한지 알아보자.

 

 

const str = 'hello world';
console.log(str + 'abc'); // hello worldabc
console.log(str.concat('abc')); // hello worldabc

일반적으로 문자열 두 개를 더해서 문자열 합치는 것처럼 concat() 함수도 동일한 결과를 보인다.

 

 

 

const str = 'hello world';
console.log(str.concat('abc', '123', '456')); // hello worldabc123456

concatd() 함수는 두 개 이상의 문자열을 받을 수 있고 그 결과로 문자열 한 개로 합친다.

 

 

 

const str = 'hello world';
console.log(str.concat(' abc')); // hello world abc
console.log(str.concat(' ', 'abc')); // hello world abc

만약 문자열 여러 개를 합칠 때 합치는 문자열 사이마다 공백이 필요하면 위와 같은 방법으로 공백을 넣을 수 있다.

 

 

 

const str = 'hello world';
console.log(str.concat(1,2,3)); // hello world123

console.log(str.concat(true)); // hello worldtrue

console.log(str.concat(null)); // hello worldnull

console.log(str.concat(undefined)); // hello worldundefined

concat() 함수는 문자열뿐만 아니라 다른 데이터 타입도 받아들인다: (Number, Boolean, Null, Undefined, Array, Object).

합쳐진 데이터의 타입은 문자열이다.

 

 

 

const str = 'hello world';
console.log(str.concat([])); // hello world
console.log(str.concat([1,2,3])); // hello world1,2,3
console.log(str.concat(["1",2,3])); // hello world1,2,3

배열도 마찬가지로 받아들여진다.

특이점은 배열의 요소만 문자열에 합쳐지는 게 아니고, 요소 사이에 있는 콤마(,)도 합친 데이터에 포함된다.

 

 

 

const str = 'hello world';
console.log(str.concat({})); // hello world[object Object]
console.log(str.concat({name: 'john', age: 10})); // hello world[object Object]

객체도 받아들여지지만 합친 문자열에 [object Object]라고 나타나기 때문에 concat() 함수 사용에 객체를 넣는 것은 권하진 않는다.

 

반응형