javascript 配列を文字列に変換する
- 作成日 2022.02.26
- 更新日 2022.10.22
- javascript
- javascript

javascriptで、配列を文字列に変換するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 106.0.5249.103
文字列に変換
文字列に変換するには「toString」で文字にした後に、カンマを除くため「replace」を使用します。
[配列].toString().replace(/,/g,'')
実際に、実行して確認してみます。
'use strict'
const arr = ['hello', 'wordl', '!!'].toString()
console.log(arr) // hello,wordl,!!
console.log(arr.replace(/,/g,'')) // hellowordl!!
実行結果

ES2021からは「replaceAll」も使用することが可能です。
const arr = ['hello', 'wordl', '!!'].toString()
console.log( arr.replaceAll(',','') ) // hellowordl!!
「toString()」を使用する以外には、「join」や「文字列」に変換する以下の方法もあります。
const arr = ['hello', 'wordl', '!!'];
console.log( arr.join('') ); // hellowordl!!
console.log( arr.join().replaceAll(',','') ); // hellowordl!!
console.log( String(arr).replaceAll(',','') ); // hellowordl!!
console.log( (arr+'').replaceAll(',','') ); // hellowordl!!
サンプルコード
以下は、
「実行」ボタンをクリックした際に、用意した配列に対して「join」で「-」区切りで文字列に変換した結果を表示するサンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.tailwindcss.com"></script>
</head>
<script>
let arr = ['abc', 'def', 'ghi']
const hoge = () => {
foo.innerHTML = arr.join('-')
}
window.onload = () => {
bar.innerHTML = `配列 : ${arr}`
btn.onclick = () => { hoge() };
}
</script>
<body>
<div class="container mx-auto my-56 w-64 px-4">
<div id="sample" class="flex flex-col justify-center">
<h1 id="bar" class="font-semibold text-rose-500 text-lg mr-auto"></h1>
<h1 class="font-semibold text-rose-500 text-lg mr-auto">実行結果</h1>
<p id="foo" class="font-semibold text-lg mr-auto"></p>
<button id="btn"
class="mb-2 md:mb-0 bg-transparent hover:bg-violet-500 text-violet-700 font-semibold hover:text-white py-2 px-4 border border-violet-500 hover:border-transparent rounded">
実行
</button>
</div>
</div>
</body>
</html>
実行結果を確認すると、変換されていることが確認できます。

-
前の記事
osquery 実行結果の表示形式を変更する 2022.02.26
-
次の記事
python PySimpleGUIでtreeのヘッダーのfontとサイズを設定する 2022.02.26
コメントを書く