Stringオブジェクトを拡張

prototypeによるメソッド定義は、ビルトインのクラスに対して行うこともできる。Stringクラスに追加しておくと役立つメソッドを紹介します。

startsWith

// 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;
}

endsWith

// 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);
}

trim

// trim 前後の空白文字を切り落とす
String.prototype.trim = function() {
    return this.replace(/^¥s+|¥s+$/g, "");
}
 
var hoge = "  abcdef   ";
hoge = hoge.trim();    // hoge == "abcdef"

isBlank

// isBlank 空白文字列のみで構成されているかどうか調べる
String.prototype.isBlank = function() {
    return this.trim() == ""
}
 
"".isBlank();        // true
"\t \n".isBlank();   // true

isEmpty

// isEmpty 長さ0の文字列かどうか調べる
String.prototype.isEmpty = function() {
    return this == ""
}
 
"".isEmpty();        // true
"\t \n".isEmpty();   // false
 
javascript/extendsstring.txt · 最終更新: 2008/07/03 19:14 (外部編集)
 
特に明示されていない限り、本Wikiの内容は次のライセンスに従います:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki