2008/02/12 18:34

Javascript Trim Others

펌: http://www.somacon.com/p355.php



Javascript Trim LTrim and RTrim Functions



Description



This set of Javascript functions trim or remove whitespace from the ends of strings. These functions can be stand-alone or attached as methods of the String object. They can left trim, right trim, or trim from both sides of the string. Rather than using a clumsy loop, they use simple, elegant regular expressions. The functions are granted to the public domain.



Javascript Trim Member Functions



Use the code below to make trim a method of all Strings. These are useful to place in a global Javascript file included by all your pages.


String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
return this.replace(/\s+$/,"");
}

// example of using trim, ltrim, and rtrim
var myString = " hello my name is ";
alert("*"+myString.trim()+"*");
alert("*"+myString.ltrim()+"*");
alert("*"+myString.rtrim()+"*");



Javascript Trim Stand-Alone Functions



If you prefer not to modify the string prototype, then you can use the stand-alone functions below.


function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
return stringToTrim.replace(/\s+$/,"");
}

// example of using trim, ltrim, and rtrim
var myString = " hello my name is ";
alert("*"+trim(myString)+"*");
alert("*"+ltrim(myString)+"*");
alert("*"+rtrim(myString)+"*");

트랙백

이 글과 관련된 글 쓰기 (트랙백 보내기)
TrackbackURL : http://ilovejava.egloos.com/tb/1408186 [도움말]

덧글

덧글 입력 영역

라이프로그