目次
+演算子で結合する
文字列 + 文字列 |
<script>
console.log("ABC" + "DE"); // ABCDE
console.log("ABC" + 123); // ABC123
</script>
2行目は、+演算子で文字列同士を結合しています。
4行目のように文字列と数値を結合することもできます。
代入演算子で結合する(+=)
変数 += 文字列 |
<script>
let a = "ABC";
a += "DE";
console.log(a); // ABCDE
</script>
3行目は、代入演算子(+=)で文字列を結合しています。
文字列を連結する(concat)
str.concat(string2[, string3, ..., stringN]) |
<script>
const a = "red";
const b = "blue";
console.log(a.concat(b)); // redblue
console.log(a.concat("---", b)); //red---blue
console.log(a.concat("---", b, "***")); //red---blue***
</script>
concatメソッドは、引き数を増やすことができ、増やした分結合されます。
concatは連結という意味です。
文字列を繰り返す(repeat)
str.repeat(count) |
<script>
const a = "A";
console.log(a.repeat(2)); // AA
const b = "ABC";
console.log(b.repeat(2)); // ABCABC
</script>
改行を含んだ文字列(テンプレートリテラル)
`文字列` |
<script>
const a = `Hello
World`;
alert(a);
</script>
バックコーテションの入力は、shiftを押しながら@を押します。
2,3行目は、改行がある文字列をバックコーテションで囲んでいます。
5行目のアラートでは、改行がある文字列が表示されます。
テンプレートリテラル(テンプレート文字列)で変数を使用
`文字列${変数}文字列` |
- 文字列をバックコーテーション(`)で括り、その中で${変数}と書くと変数を展開できます。
- バックコーテションの入力は、shiftを押しながら@を押します。
<script>
const a = "red";
console.log(`color is ${a}.`); // color is red.
const b = 1;
const c = 2;
console.log(`1+2= ${b + c}.`); // 1+2= 3.
</script>
3行目は、2行目の変数を文字列内で結合して表示しています。
7行目のように、${ }内で計算もできます。
関数の実行
以下のようにテンプレート文字列内で関数も実行できます。
<script>
function calc(num1, num2) {
return num1 + num2;
}
console.log(`The total is ${calc(1,2)}.`); // The total is 3.
</script>
関連の記事