본문 바로가기

Programming/JavaScript

자바스크립트에서 문자열앞의 공백의 자리수를 체크하고 그공백을제거하는 방법

<script>
/**
* 좌우 공백 제거
*/
String.prototype.trim = function()
{
return this.replace(/(^\s*)|(\s*$)/g, "");
}

/**
* 텍스트 좌측 부분의 공백 갯수
*/
String.prototype.leftSpaceQuantity = function()
{
var count = 0;

for( i = 0; i < this.length; i++ )
{
if( this.charAt(i) == ' ' )
count++;
else
break;
}

return count;
}

/**
* 텍스트 우측 부분의 공백 갯수
*/
String.prototype.rightSpaceQuantity = function()
{
var count = 0;

for( i = this.length - 1; i >= 0; i-- )
{
if( this.charAt(i) == ' ' )
count++;
else
break;
}

return count;
}

var test = " 테스트 ";

alert( "공백 제거 전 : " + test );
alert( "좌우 공백 제거 후 : " + test.trim() );
alert( "좌측 공백 갯수 " + test.leftSpaceQuantity() );
alert( "우측 공백 갯수 " + test.rightSpaceQuantity() );
</script>