inazuma code :文字列のメソッド
文字列型(string
)には、以下のメソッドが用意されています。
いずれも 非破壊的 で、呼び出し元の文字列は変更されず、新しい値を返します。
メソッド一覧
メソッド | 引数 | 返り値 | 説明 |
---|---|---|---|
size() | なし | number | 文字列の長さを返す(マルチバイト対応) |
to_upper() | なし | string | 全ての文字を大文字に変換 |
to_lower() | なし | string | 全ての文字を小文字に変換 |
capitalize() | なし | string | 先頭文字を大文字に、残りを小文字に変換(マルチバイト対応) |
to_int() | なし | number | 整数に変換(完全一致で整数形式の文字列でない場合は例外) |
to_float() | なし | number | 浮動小数に変換(指数表記可、完全一致で数値形式でない場合は例外) |
replace(search, replace) | string | array search, string | array replace | string | 指定文字列を置換(複数の文字列を同時に置換可能) |
repeat(count) | number count | string | 指定回数だけ繰り返し結合 |
pad_start(length, padStr?) | number length, string padStr = " " | string | 左側を指定文字で埋める |
pad_end(length, padStr?) | number length, string padStr = " " | string | 右側を指定文字で埋める |
trim(characters?) | string characters = " \t\n\r\0\x0B" | string | 先頭と末尾の指定文字を削除(デフォルトは空白類) |
split(delimiter) | string delimiter | array<string> | 区切り文字で分割して配列化 |
substring(start, length?) | number start, number? length | string | 開始位置から指定長さを抽出(負のインデックス不可、マルチバイト対応) |
slice(start, end?) | number start, number? end | string | 開始位置から終了位置までを抽出(負のインデックス不可) |
index_of(needle, offset?) | string needle, number offset = 0 | number | 最初に一致した位置を返す(見つからなければ -1 ) |
char_at(index) | number index | string | 指定位置の1文字(マルチバイト対応) |
starts_with(prefix) | string prefix | boolean | 指定文字列で開始しているか判定 |
ends_with(suffix) | string suffix | boolean | 指定文字列で終了しているか判定 |
includes(needle) | string needle | boolean | 指定文字列を含むか判定 |
match(pattern) | string pattern(正規表現) | array<string> | null | 正規表現に一致した結果配列(キャプチャグループ含む)、一致しない場合は null |
nl2br(is_xhtml?) | boolean is_xhtml = true | string | 改行を <br />\n に変換(XHTML 出力はデフォルト true) |
使用例:
"hello"->size(); // 5
"hello"->to_upper(); // "HELLO"
"HELLO"->to_lower(); // "hello"
"hello"->capitalize(); // "Hello"
"123"->to_int(); // 123
"123.456"->to_float(); // 123.456
"1.23e4"->to_float(); // 12300.0
"hello world"->replace("world", "everyone"); // "hello everyone"
"hello"->repeat(3); // "hellohellohello"
"hello"->pad_start(10, " "); // " hello"
"hello"->pad_end(10, " "); // "hello "
" hello "->trim(); // "hello"
"hello world"->split(" "); // ["hello", "world"]
"hello world"->substring(0, 5); // "hello"
"hello world"->slice(6, 11); // "world"
"hello world"->index_of("world"); // 6
"hello"->char_at(1); // "e"
"hello world"->starts_with("hello"); // true
"hello world"->ends_with("world"); // true
"hello world"->includes("world"); // true
"hello world"->match("/(hello) (world)/");
// ["hello world", "hello", "world"]
"hello\nworld"->nl2br();
// "hello<br />\nworld"
仕様補足
- 全てのメソッドは非破壊的です。
replace
は配列を渡して複数の文字列を同時に置換できます。trim
は削除する文字を指定できます。