반응형

Javascript에서 변수 값의 길이는 구해야 할 경우, 함수를 통해 이를 해결 할 수 있습니다. 
이 함수는 바로 length (길이)이며 이는 활용하여 문자열이나 숫자의 길이를 구해 보겠습니다.

사용법

변수.length

위의 함수를 쓰게 되면 해당 String 변수안의 문자열의 길이를 구할 수 있습니다.
예를 들면 A변수 안에 ABCDE라는 값이 있을 경우 5라는 값을 리턴하게 됩니다.

 

length 예제

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<script src="http://code.jquery.com/jquery-3.4.1.js"></script>
<script type="text/javascript">

function check_length(){
	
	var size_chk = $("#test_case").val();
	
	alert("데이터 사이즈 : "+size_chk.length);
	
}



</script>
</head>
<body>
<input type="text" id="test_case" value="데이터 체크">
<input type="button" onclick="check_length()" value="버튼"> 
</body>
</html>

결과

숫자 예제

숫자 변수에 length를 적용하게 되면
위와 같이 undefined에러가 발생하게 됩니다.


length 함수가 문자열에만 적용되므로
해당 변수의 값을 .toString을 통해 문자로 변환해 주면 문제가 해결 됩니다.

변환 소스

function check_length(){
	
	var size_chk = 12345678;
	
	alert("데이터 사이즈 : "+size_chk.toString().length);
	
}

결과

for문과 substring을 이용한 응용 예제

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<script src="http://code.jquery.com/jquery-3.4.1.js"></script>
<script type="text/javascript">

function check_length(){
	
	var size_chk = $("#test_case").val();
	
	for(var i=0; i< size_chk.length; i++){
		console.log(size_chk.substring(i,i+1));	
	}
}



</script>
</head>
<body>
<input type="text" id="test_case" value="가나다라마바사">
<input type="button" onclick="check_length()" value="버튼"> 
</body>
</html>

결과

Javascript에서 문자열 변수에 length를 구할 수 있으며

이를 통해 for문이나 등을 이용하여 데이터를 처리할 수 있습니다.

반응형

+ Recent posts