JavaScriptでJavaのStringクラスのメソッドを実装
追記:String#endsWith
を修正&別の実装方法を追加 (2009/08/17 )
気が向いたので
JavaのStringクラスで実装されているメソッドをJavaScriptで実装してみた。
接頭辞判定:String#startsWith
文字列の指定されたインデックス以降の部分文字列が、
指定された接頭辞で始まるかどうかを判定する。
String.prototype.startsWith = function(prefix, toffset) { var i = 0; if(toffset && (typeof toffset === 'number')) { i = toffset; } return this.slice(i).indexOf(prefix) === 0; }; var text = 'ABCDEFG'; text.startsWith('ABC'); // true text.startsWith('BC'); // false text.startsWith('CDE', 2); // true text.startsWith('AB', 2); // false
接尾辞判定:String#endsWith
文字列が、指定された接尾辞で終るかどうかを判定する。
String.prototype.endsWith = function(suffix) { var sub = this.length - suffix.length; return (sub >= 0) && (this.lastIndexOf(suffix) === sub); }; var text = 'ABCDE'; console.log(text.endsWith('ABC')); // false console.log(text.endsWith('DE')); // true var text2 = 'AAA'; console.log(text2.endsWith('A')); // true console.log(text2.endsWith('AAAA')); // false
もしくは、startsWith
メソッドを用いて
String.prototype.endsWith = function(suffix) { return this.startsWith(suffix, this.length - suffix.length); };
文字列のトリム:String#trim
文字列のtrim(空白削除)を行う。
String.prototype.trimLeft = function() { return this.replace(/^\s+/,''); }; String.prototype.trimRight = function() { return this.replace(/\s+$/,''); }; String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,''); }; var text = ' ABCDEFG '; text.trimLeft(); // 'ABCDEFG ' text.trimRight(); // ' ABCDEFG' text.trim(); // 'ABCDEFG'