46
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【JavaScript】文字列を任意の文字数で分割し、配列を作成する方法

Last updated at Posted at 2019-06-20

はじめに

JavaScriptで文字列を任意の文字数で分割し、配列を作成する方法です。
結論からいうと正規表現での取得が一番スッキリ書けました。
他にもいくつか試したの方法も記載しておきます。

例ではUGGUGUUAUUAAUGGUUUの文字列を三文字毎に分割して["UGG", "UGU", "UAU", "UAA", "UGG", "UUU"]の配列を作成しています。

正規表現


const rna = "UGGUGUUAUUAAUGGUUU";
let cdn1 = rna.match(/.{3}/g);
console.log(cdn1)
// ["UGG", "UGU", "UAU", "UAA", "UGG", "UUU"]

substr


const rna = "UGGUGUUAUUAAUGGUUU";
let cdn2 = [];
for (let i = 0; i < rna.length / 3; i++) {
    cdn2.push(rna.substr(i * 3, 3));
}
console.log(cdn2)
// ["UGG", "UGU", "UAU", "UAA", "UGG", "UUU"]

substring


const rna = "UGGUGUUAUUAAUGGUUU";
let cdn3 = [];
for (let i = 0; i < rna.length; i += 3) {
    cdn3.push(rna.substring(i, i + 3));
}
console.log(cdn3);
// ["UGG", "UGU", "UAU", "UAA", "UGG", "UUU"]

slice

const rna = "UGGUGUUAUUAAUGGUUU";
let cdn4 = [];
for (let i = 0; i < rna.length; i+=3) {
    cdn4.push(rna.slice(i, i+3));
}
console.log(cdn4);
// ["UGG", "UGU", "UAU", "UAA", "UGG", "UUU"]

reduce

@hayashi-ay さんより教えて頂いたものです。

const rna = [..."UGGUGUUAUUAAUGGUUU"];
let cdn5 = rna.reduce( (acc, c, i ) =>  i % 3 ? acc : [...acc, rna.slice( i, i+3 ).join('') ], [] );
console.log(cdn5);

参考URL

JavaScriptで、文字列を、指定した文字数で分割して、配列で返す

46
27
3

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
46
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?