본문 바로가기
자바스크립트

[JAVASCRIPT] 문자열 합치기 - concat() / 배열의 요소들을 하나의 문자열로 합치기 - join()

by jaewooojung 2019. 8. 6.

JAVASCRIPT


concat / join

자바스크립트에서 문자열을 합치는 방법입니다.

 

1. + 사용

const str1 = "Hello";
const str2 = " World";

console.log(str1 + str2); // Hello World

 

 

2. 여러 개의 문자열 합치기 concat

str.concat(string2, string3[, ..., stringN]);

str에 인자로 전달한 문자열들을 모두 합쳐서 새로운 문자열을 반환합니다.

 

예시 1

두 문자열을 합칩니다.

const strA = "A friend to all";
const strB = "is a friend to none";
const message = strA.concat(strB);
console.log(message); // "A friend to allis a friend to none"

 

예시 2

여러 문자열을 인자로 넣을 수 있습니다. 공백을 넣어서 두 문자열 사이를 한 칸 띄어줍니다.

const strA = "A friend to all";
const strB = "is a friend to none";
const message = strA.concat(" ", strB);
console.log(message); // "A friend to all is a friend to none"

 

 

3. 배열의 요소들을 문자열로 합치기 join

arr.join([separator]);

구분자(separator)를 활용해서 배열의 모든 요소를 하나의 문자열로 합쳐줍니다.

 

구분자로 공백(" ")을 전달하여 모든 단어가 한 칸씩 띄어서 합쳐졌습니다.

const arr = ["A", "friend", "to", "all", "is", "a", "friend", "to", "none"];
const message = arr.join(" ");
console.log(message); // "A friend to all is a friend to none"

 

 

구분자를 전달하지 않으면 자동으로 콤마(,)로 구분됩니다.

const arr = ["A", "friend", "to", "all", "is", "a", "friend", "to", "none"];
const message = arr.join();
console.log(message); // "A,friend,to,all,is,a,friend,to,none"

MDN document - String.prototype.concat()

 

String.prototype.concat() - JavaScript | MDN

concat() 메서드는 매개변수로 전달된 모든 문자열을 호출 문자열에 붙인 새로운 문자열을 반환합니다.

developer.mozilla.org

MDN document - Array.prototype.join()

 

Array.prototype.join() - JavaScript | MDN

join() 메서드는 배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.

developer.mozilla.org

 



        
답변을 생성하고 있어요.