JavaScript(Jscript)でtrimについて

trim(トリム)とは、文字列から先頭および末尾の空白を取り除くことです。JavaScript(Jscript)には、trim関数がありません。そこで、Stringクラスを拡張して、正規表現を用いてtrimメソッドを追加します。

Stringクラスを拡張して、trimメソッドを追加

<script language="JavaScript">
// trim関数定義
if(!String.prototype.trim){
	String.prototype.trim = function(){
		return this.toString().replace(/^\s+|\s+$/g,'');
	};
	String.prototype.lTrim = function(){
		return this.toString().replace(/^\s+/g,'');
	};
	String.prototype.rTrim = function(){
		return this.toString().replace(/\s+$/g,'');
	};
}
TestTrim();
function TestTrim(){
	//Stringクラスを拡張して追加したtrimメソッドの使用例
	var s = "     ABCD     ";
	alert("*" + s.trim() + "*");
	alert("*" + s.lTrim() + "*");
	alert("*" + s.rTrim() + "*");
}
</script>

inserted by FC2 system