javascript:extendsstring
差分
このページの2つのバージョン間の差分を表示します。
javascript:extendsstring [2008/07/03 10:14] – 外部編集 127.0.0.1 | javascript:extendsstring [2015/08/20 07:03] (現在) – 削除 nullpon | ||
---|---|---|---|
行 1: | 行 1: | ||
- | ====== Stringオブジェクトを拡張 ====== | ||
- | prototypeによるメソッド定義は、ビルトインのクラスに対して行うこともできる。Stringクラスに追加しておくと役立つメソッドを紹介します。 | ||
- | ===== startsWith ===== | ||
- | <code javascript> | ||
- | // startsWith この文字列がprefixで始まっていればtrue | ||
- | String.prototype.startsWith = function(prefix) { | ||
- | if (prefix.length > this.length) return false; | ||
- | return prefix == this.substring(0, | ||
- | } | ||
- | |||
- | var hoge = " | ||
- | hoge.startsWith(" | ||
- | |||
- | // startsWith別実装 | ||
- | String.prototype.startsWith = function(prefix) { | ||
- | if (prefix.length > this.length) return false; | ||
- | return this.indexOf(prefix) == 0; | ||
- | } | ||
- | </ | ||
- | ===== endsWith ===== | ||
- | <code javascript> | ||
- | // endsWith この文字列がsuffixで終わっていればtrue | ||
- | String.prototype.endsWith = function(suffix) { | ||
- | if (suffix.length > this.length) return false; | ||
- | return suffix == this.slice(~suffix.length + 1); | ||
- | } | ||
- | |||
- | var hoge = " | ||
- | hoge.endsWith(" | ||
- | |||
- | // endsWith別の実装 | ||
- | String.prototype.endsWith = function(suffix) { | ||
- | if (suffix.length > this.length) return false; | ||
- | return this.lastIndexOf(suffix) == (this.length - suffix.length); | ||
- | } | ||
- | </ | ||
- | ===== trim ===== | ||
- | <code javascript> | ||
- | // trim 前後の空白文字を切り落とす | ||
- | String.prototype.trim = function() { | ||
- | return this.replace(/ | ||
- | } | ||
- | |||
- | var hoge = " | ||
- | hoge = hoge.trim(); | ||
- | </ | ||
- | ===== isBlank ===== | ||
- | <code javascript> | ||
- | // isBlank 空白文字列のみで構成されているかどうか調べる | ||
- | String.prototype.isBlank = function() { | ||
- | return this.trim() == "" | ||
- | } | ||
- | |||
- | "" | ||
- | "\t \n" | ||
- | </ | ||
- | ===== isEmpty ===== | ||
- | <code javascript> | ||
- | // isEmpty 長さ0の文字列かどうか調べる | ||
- | String.prototype.isEmpty = function() { | ||
- | return this == "" | ||
- | } | ||
- | |||
- | "" | ||
- | "\t \n" | ||
- | </ |
javascript/extendsstring.1215080045.txt.gz · 最終更新: 2015/08/20 07:03 (外部編集)