티스토리 뷰

[자바스크립트 문자열 자르기 Split]

자바스크립트에서.. split 을 쓸경우..

var s_data = "2005-03-25";  // 잘라야 되는 값..
var array_data = s_data.split("-");  // split 함수사용..
var s_year = array_data[0];   // 잘라진 값 배열..
var s_month = array_data[1];
var s_day = array_data[2];



[자바스크립트 문자열 길이대로 자르기]

function cutStr(str,limit){
var tmpStr = str;
var byte_count = 0;
var len = str.length;
var dot = "";

for(i=0; i<len; i++){
byte_count += chr_byte(str.charAt(i));
if(byte_count == limit-1){
if(chr_byte(str.charAt(i+1)) == 2){
tmpStr = str.substring(0,i+1);
dot = "...";
}else {
if(i+2 != len) dot = "...";
tmpStr = str.substring(0,i+2);
}
break;
}else if(byte_count == limit){
if(i+1 != len) dot = "...";
tmpStr = str.substring(0,i+1);
break;
}

}
document.writeln(tmpStr+dot);
return true;
}
function chr_byte(chr){
if(escape(chr).length > 4)
return 2;
else
return 1;
}
 

사용은 문자열을 출력할 곳에 <script>cutStr("길이가 긴 원래의 문자열",5)</script>와 같이 써주시면 바이트 단위로 자르고 한글과 같이 2byte가 되는 글자는 1byte줄여서 출력합니다.


[시작인덱스+끝인덱스로 자르기]

실행시켜 보시면...이해가 될 겁니다.. 도움이 되시길 ^^*
======================================================
<SCRIPT LANGUAGE="JavaScript">
str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.write("str returns: " + str + "<BR>");
document.write("str.substring(0, str.length) returns: ");
document.write(str.substring(0, str.length) + "<BR>");
document.write("str.substring(0, 1) returns: ");
document.write(str.substring(0, 1) + "<BR>");
document.write("str.substring(0, 5) returns: ");
document.write(str.substring(0, 5) + "<BR>");
document.write("str.substring(-5, 5) returns: ");
document.write(str.substring(-5, 5) + "<BR>");
document.write("str.substring(8, 13) returns: ");
document.write(str.substring(8, 13) + "<BR>");
document.write("str.substring(8, 99) returns: ");
document.write(str.substring(8, 99) + "<BR>");
document.write("str.substring(9, 9) returns: ");
document.write(str.substring(9, 9) + "<BR>");
document.write("str.substring(9, 8) returns: ");
document.write(str.substring(9, 8) + "<BR>");
document.write("str.substring(9, 0) returns: ");
document.write(str.substring(9, 0) + "<BR>");
document.write("str.length returns: ");
document.write(str.length + "<BR>");
document.write("str.substring( str.length-3, str.length) returns: ");
document.write(str.substring( str.length-3, str.length) + "<BR>");
</SCRIPT>

================================================
str.substring(시작인덱스, 끝인덱스)
================================================
 
출처 : PHP스쿨 




[자바스크립트 :: 문자열 우측에서 잘라서 가져오기]

예로써 주문시 적립금을 입력한 금액이 1000원 단위로만 입력했는지 확인하고자 한다면 우측 3자리와 비교해야하므로 이때 substr을 이용하면됨
"5700".length 4이므로 여기에 4 - 3 = 1 위치 부터 문자를 받아옴
즉 결과는 "700"을 받아 오게됨
 
 
<form name="form" method="post">
  <input type="text" name="reservein" value="5700">
</form>
<script>
var ff = document.form.reservein.value;
// 비교구문은 1000보다 작은지 또는 아래처럼 000 일치한지 처럼 자신의 코딩 스타일로 구현하면됨. ^^
if(ff.substr((ff.length-3) != "000") { 
  alert("1,000원 단위로 입력하세요!");
}
</script>

출처 : http://saybox.tistory.com/53
댓글
안내
궁금한 점을 댓글로 남겨주시면 답변해 드립니다.