LoginSignup
4
2

More than 5 years have passed since last update.

独自の文字列を二次元配列にする

Last updated at Posted at 2017-02-08

概要

  • 独自の規則に従った文字列から二次元配列を生成する。
  • 規則性がありつつ、ある程度柔軟性も持たせる。

ルール

  • 1階層目の配列区切りはカンマ。
  • 2階層目の配列区切りは半角スペース。
  • 文字列前後のスペースはないものとして扱う。
  • カンマの前後にスペースがあっても、そのスペースはないものとして扱う。
  • スペースが2つ以上連続で続いている場合は1つ扱いとする。
'hoge 123, fuga 456' -> [["hoge", "123"], ["fuga", "456"]]
'sample   test   ,     example     text' ->  [["sample", "test"], ["example", "text"]]

サンプルコード

var str = 'word texttext  test1  , title example.com';
var ary = str.trim().split(',').map(function(item){
  return item.trim().replace(/\s+/g,' ').split(' ');
});

console.log(ary); // [["word", "texttext", "test1"], ["title", "example.com"]]

/* 関数化 */
var dArray = function(str) {
  return str.trim().split(',').map(function(item) {
    return item.trim().replace(/\s+/g, ' ').split(' ');
  });
};

var test = dArray(str);

使った関数

関数名 効果
split 文字列を任意の文字列で区切り、配列を生成
trim 文字列の前後の空白を削除
replace 文字列の置換
map 配列を元に新たな配列を生成する

まとめ

  • オレオレ文法から任意の配列が作れる。
  • 関数を組み合わせることで、ちょっとした独自言語のようなことができる。
4
2
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2