LoginSignup
0
0

More than 3 years have passed since last update.

【JavaScript】文字列の操作いろいろ

Last updated at Posted at 2020-05-13

文字列を操作

- 文字列の文字数を取得する
- .length( ) を使う

const str = 'hello';

console.log(str.length);
// 実行結果
// 5
  • 文字列中の指定した文字を取得する
  • .substring( )を使う
const str = 'hello';
 //定数.substring(開始位置,終了位置)
console.log(str.substring(1,3));
// 実行結果
//el
  • 配列のような記法で取得することもできる  ※配列と同じ操作はできない
const str = 'hello';
console.log(str[1]);
// 実行結果
//e

配列の要素を結合して文字列にする

  • join( )を使う
const today = [2020, 5, 13];
  //join()の引数に結合するときの文字列を渡す
  //空白でも良い。その場合 join('')とする
console.log(day.join('/'));
// 実行結果
// '2020/5/13'

文字列を分割して配列化する(上記の逆パターン)

  • split( )を使う
const today = '2020/5/13';
   //split()の引数に渡した区切り文字のところで分割する
console.log(day.split('/'));
// 実行結果
//[2020,5,13]

  //第2引数に個数も指定できる
console.log(day.split('/',2));
// 実行結果
// [2020,5]
  • 上記の応用で分割代入を使う
const today = '2020/5/13';
  //分割した要素を定数に代入する
const[year,month,day] = day.split('/');
console.log(year);
console.log(month);
console.log(day);

// 実行結果
// 2020
// 5
// 13
0
0
0

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
0
0