JavaScript에서는 Trim을 사용해야 하는 곳이 많지만 JavaScript에는 독립적인 Trim 함수나 사용할 메소드가 없기 때문에 목적을 달성하려면 Trim 함수를 직접 작성해야 합니다.
옵션 1:
프로토타입 모드, 즉 obj.trim() 형식으로 호출되는 이 메서드는 간단하고 다음과 같이 정의됩니다
.
/**
* 양쪽 끝의 공백 삭제
*/
String.prototype.trim=함수()
{
return this.replace(/(^s*)|(s*$)/g, ”);
}
/**
* 왼쪽 공백 삭제
*/
String.prototype.ltrim=함수()
{
return this.replace(/(^s*)/g,”);
}
/**
* 오른쪽 공백 삭제
*/
String.prototype.rtrim=함수()
{
return this.replace(/(s*$)/g,”);
}
</script>
사용 예는 다음과 같습니다.
<script type="text/javascript">
Alert(document.getElementById('abc').value.trim());
Alert(document.getElementById('abc').value.ltrim());
Alert(document.getElementById('abc').value.rtrim());
</script>
옵션 2:
도구 모드, 즉 Trim(obj) 형식으로 호출되는 이 메서드는 특별한 처리 요구에 사용할 수 있으며 다음과 같이 정의됩니다.
<스크립트 유형="텍스트/자바스크립트">
/**
* 양쪽 끝의 공백 삭제
*/
함수 트림(str)
{
return str.replace(/(^s*)|(s*$)/g, ”);
}
/**
* 왼쪽 공백 삭제
*/
함수ltrim(str)
{
return str.replace(/(^s*)/g,”);
}
/**
* 오른쪽 공백 삭제
*/
functionrtrim(str)
{
return str.replace(/(s*$)/g,”);
}
</script>
사용 예는 다음과 같습니다.
<script type="text/javascript">
Alert(trim(document.getElementById('abc').value));
Alert(ltrim(document.getElementById('abc').value));
Alert(rtrim(document.getElementById('abc').value));
</script>