https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String
文字列の長さ取得
"てst".length
".length
結果 :
リンクタグの作成
1 |
戻り値
"google".anchor("https://www.google.co.jp")
"".anchor("")結果 :
こんなものがあるのか
そのほかにbold(太字)やstrike(取り消し線)もあるが非推奨?
文字列結合
1 | "con" .concat( "cat" ) |
普通に連結する
"con"+"cat"
"test".concat( "" )
結果 :
文字列が指定した位置から末尾が一致するか確認する
1 2 | "endsWith" .endsWith( "With" ) // 末尾チェック "endsWith" .endsWith( "dsW" , 5) // endsW の末尾チェック |
"endWith".endsWith( "" )
結果 :
指定した位置から先頭が一致するか確認する
1 2 | "startWith" .startsWith( "start" ) "startWith" .startsWith( "With" , 5) |
"startWith".startsWith( "" )
結果 :
文字列の存在チェック
1 | "test" .includes( "es" ) |
IEやOperaでは対応していないらしい
全ブラウザで対応した場合は下記のindexOfを使用する
"test".includes( "" )
結果 :
文字列が出現した位置を返す
1 | "test" .indexOf( "es" ) !== -1 |
1 | "test" .lastIndexOf( "es" ) !== -1 |
"test".indexOf( "" )
結果 :
正規表現による文字列のマッチング
1 | "test" .match( "t.*t" ) |
マッチした値が配列で返ってくる
存在チェックなどに使用する。
"test regex".match( "" ) !== null
結果 :
正規表現に一致する文字列の位置を返す
1 | "test" .search( "t.*t" ) !== -1 |
"test regex".search( "" )
結果 :
文字列の置き換え
1 | "replace test" .replace( "replace" , "置き換え" ) |
戻り値
"置き換え test"
正規表現も可能
1 | "replace test" .replace(/(re.*ce )(test)/, "○$1○$2" ) |
戻り値
"○replace ○test"
"replace test".replace( "", "" )
結果 :
ちょっと複雑なので詳しくは以下を参照
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/replace
文字列の切り出し
1 | "slice test" .slice(6) // 6文字目から最後まで切り出し |
"test"
1 | "slice test" .slice(6, 9) // 6文字目から9文字目を切り出し |
"tes"
マイナスを指定した場合末尾からになる。
"slice test".slice( , )
結果 :
指定した位置からn文字切り出し
1 | "substr() test" .substr(9, 4) |
"test"
上記と場合によって使い分け
"substr() test".substr( , )
結果 :
開始位置と終了位置から文字列切り出し
1 | "substring test" .substring(10, 14) |
"test"
"substring test".substring( "", "" )
結果 :
文字列分割
1 | "split,test" .split( "," ) |
配列で返ってくる
["split". "test"]
"".split( "," ).join("_")
結果 :
大文字から小文字へ変換
1 | "TEST" .toLowerCase() |
"".toLowerCase()
結果 :
小文字から大文字へ変換
1 | "test" .toUpperCase() |
"".toUpperCase()
結果 :
両端の空白削除
1 | " test " .trim() |
"test"
半角、全角スペース、タブなどもトリムされる。
"".trim()
結果 :
左の空白削除
1 | " test" .trimLeft() |
"".trimLeft()
結果 :
右の空白削除
1 | "test " .trimRight() |
"".trimRight()
結果 :
文字列のパディング
FireFoxでpadStartというものがあるが標準ではないので推奨されない
以下のスニペットを利用する
1 2 3 | var num = 999 var padding = "00000" var result = (padding + num).slice(-padding.length) |
numが0埋めする桁数を超える可能性がある場合は以下
1 2 3 4 | var num = 999999 var padding = "00000" var result = (num+ "" ).length > padding.length ? num + "" : (padding+num).slice(-padding.length) console.log(result) |
結果 :
文字列をJavaScriptとして実行する
eval is evil