ユーザ用ツール

サイト用ツール


javascript:extendsstring

差分

このページの2つのバージョン間の差分を表示します。

この比較画面へのリンク

javascript:extendsstring [2008/07/03 10:14] – 外部編集 127.0.0.1javascript: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, prefix.length); 
-} 
- 
-var hoge = "abcdef"; 
-hoge.startsWith("abc");    // true 
- 
-// startsWith別実装 
-String.prototype.startsWith = function(prefix) { 
-    if (prefix.length > this.length) return false; 
-    return this.indexOf(prefix) == 0; 
-} 
-</code> 
-===== 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 = "abcdef"; 
-hoge.endsWith("def");    // true 
- 
-// endsWith別の実装 
-String.prototype.endsWith = function(suffix) { 
-    if (suffix.length > this.length) return false; 
-    return this.lastIndexOf(suffix) == (this.length - suffix.length); 
-} 
-</code> 
-===== trim ===== 
-<code javascript> 
-// trim 前後の空白文字を切り落とす 
-String.prototype.trim = function() { 
-    return this.replace(/^¥s+|¥s+$/g, ""); 
-} 
- 
-var hoge = "  abcdef   "; 
-hoge = hoge.trim();    // hoge == "abcdef" 
-</code> 
-===== isBlank ===== 
-<code javascript> 
-// isBlank 空白文字列のみで構成されているかどうか調べる 
-String.prototype.isBlank = function() { 
-    return this.trim() == "" 
-} 
- 
-"".isBlank();        // true 
-"\t \n".isBlank();   // true 
-</code> 
-===== isEmpty ===== 
-<code javascript> 
-// isEmpty 長さ0の文字列かどうか調べる 
-String.prototype.isEmpty = function() { 
-    return this == "" 
-} 
- 
-"".isEmpty();        // true 
-"\t \n".isEmpty();   // false 
-</code> 
javascript/extendsstring.1215080045.txt.gz · 最終更新: 2015/08/20 07:03 (外部編集)