js-text-to-array2d hi0a.com

view source

JavaScript

function textToArray2D(text){
  const array2D = text.trim().split('\n').map(line => line.split(''));
  console.log(array2D);
  return array2D;
}
function formatted(array2D){
  return '[\n' +
    array2D.map(row => '  ' + JSON.stringify(row)).join(',\n') +
  '\n]';
}

formatted 
const inputArea = document.createElement('textarea');
const btn = document.createElement('button');
const outputArea = document.createElement('textarea');
inputArea.placeholder = "例:\n001100\n011110\n000100";
document.getElementById('demo').appendChild(inputArea);
document.getElementById('demo').appendChild(btn);
document.getElementById('demo').appendChild(outputArea);
btn.textContent = 'Text to Array2D: 文字列を2次元配列に変換';
inputArea.style.width ='99%';
inputArea.style.height ='44vh';
outputArea.style.width = '99%';
outputArea.style.height = '44vh';
btn.addEventListener('click', () => {
  const inputText = inputArea.value.trim();
  const array2D = textToArray2D(inputText);
  //outputArea.value = JSON.stringify(array2D, null, 2);
  outputArea.value = formatted(array2D);
});

CSS

HTML

ページのソースを表示 : Ctrl+U , DevTools : F12

view-source:https://hi0a.com/demo/-js/js-text-to-array2d/

ABOUT

hi0a.com 「ひまあそび」は無料で遊べるミニゲームや便利ツールを公開しています。

プログラミング言語の動作デモやWEBデザイン、ソースコード、フロントエンド等の開発者のための技術を公開しています。

必要な機能の関数をコピペ利用したり勉強に活用できます。

プログラムの動作サンプル結果は画面上部に出力表示されています。

環境:最新のブラウザ GoogleChrome / Windows / Android / iPhone 等の端末で動作確認しています。

画像素材や音素材は半分自作でフリー素材配布サイトも利用しています。LINK参照。

仕様変更、API廃止等、実験途中で動かないページもあります。