ユーザ用ツール

サイト用ツール


javascript:extendsstring

文書の過去の版を表示しています。


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.1215080045.txt.gz · 最終更新: 2015/08/20 07:03 (外部編集)