JavaScript splitメソッドの使い方

JavaScript logo JavaScript

splitメソッドはStringオブジェクトを指定した文字列で分割し、Arrayオブジェクトを生成することができる。

■構文

split(String separator)
引数 – separator: 区切り文字列
戻り値 – 分割した文字列の配列

■プログラム概要

文字列 ‘My forehead is a washboard.’ を ‘ ‘( 半角スペース )で分割し、配列オブジェクトを出力する。

var str = 'My forehead is a washboard.';
var ary = str.split(' ');
console.log(ary); // 配列の要素をカンマ区切りで出力
console.log(ary[1]);
console.log(ary[4]);
■出力結果

My,forehead,is,a,washboard.
forehead
washboard.

コメント

タイトルとURLをコピーしました