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
'자바스크립트' 카테고리의 다른 글
[JAVASCRIPT] 날짜 확인하기 Date 객체 사용 방법 (0) | 2019.08.06 |
---|---|
[JAVASCRIPT] 문자열 혹은 배열이 특정 요소를 포함하는지 확인 - includes() (1) | 2019.08.06 |
[JAVASCRIPT] 문자열 나누기 - split() / 부분 문자열 추출하기 - substring() (0) | 2019.08.06 |
[JAVASCRIPT] 문자열(string)의 첫 글자를 대문자로 바꾸기 (0) | 2019.08.05 |
[JAVASCRIPT] 배열(Array)에서 특정값 삭제하기 - splice() (0) | 2019.08.04 |