'JavaScript'에 해당되는 글 17건

  1. 2008.11.05 javascript string prototype 정리
  2. 2008.10.13 오른쪽 마우스 제안
  3. 2008.09.29 javascript parseInt()
  4. 2008.09.25 마우스 움직일때 Banner이동
  5. 2008.09.25 javascript slice() 함수
  6. 2008.09.20 javascript encoding
  7. 2008.09.12 현재 Url 가져오기
posted by 준치 2008. 11. 5. 15:14

자바스크립트에서 스트링관련해서 자주 쓰이는 함수들을 정리해 놓은 포스트가 있어 소개합니다.
이정도면 유용하게 활용할수 있을것 같네요.


    1
 /*--------------------------------------------------------------------------------*\

    2  *  JavaScript framework, version 2.0

    3  *

    4  *  Date : 2006. 08. 15.

    5  *  Copyright 1998-2007 by Vricks Studio All right reserved.

    6  *  @author Jeff Yang routine@vricks.com

    7  *  자주 쓰이는 스트링 관련 prototype관련 정리

    8 \*--------------------------------------------------------------------------------*/

    9 

   10 /*--------------------------------------------------------------------------------*\

   11  *  String prototype

   12 \*--------------------------------------------------------------------------------*/

   13     //-----------------------------------------------------------------------------

   14     // 문자의 좌, 우 공백 제거

   15     // @return : String

   16     //-----------------------------------------------------------------------------

   17     String.prototype.trim = function() {

   18         return this.replace(/(^\s*)|(\s*$)/g, "");

   19     }

   20     //-----------------------------------------------------------------------------

   21     // 문자의 좌 공백 제거

   22     // @return : String

   23     //-----------------------------------------------------------------------------

   24     String.prototype.ltrim = function() {

   25         return this.replace(/(^\s*)/, "");

   26     }

   27     //-----------------------------------------------------------------------------

   28     // 문자의 우 공백 제거

   29     // @return : String

   30     //-----------------------------------------------------------------------------

   31     String.prototype.rtrim = function() {

   32         return this.replace(/(\s*$)/, "");   

   33     }

   34     //-----------------------------------------------------------------------------

   35     // 문자열의 byte 길이 반환

   36     // @return : int

   37     //-----------------------------------------------------------------------------

   38     String.prototype.byte = function() {

   39         var cnt = 0;

   40         for (var i = 0; i < this.length; i++) {

   41             if (this.charCodeAt(i) > 127)

   42                 cnt += 2;

   43             else

   44                 cnt++;

   45         }

   46         return cnt;

   47     }

   48     //-----------------------------------------------------------------------------

   49     // 정수형으로 변환

   50     // @return : String

   51     //-----------------------------------------------------------------------------

   52     String.prototype.int = function() {

   53         if(!isNaN(this)) {

   54             return parseInt(this);

   55         }

   56         else {

   57             return null;   

   58         }

   59     }

   60     //-----------------------------------------------------------------------------

   61     // 숫자만 가져 오기

   62     // @return : String

   63     //-----------------------------------------------------------------------------

   64     String.prototype.num = function() {

   65         return (this.trim().replace(/[^0-9]/g, ""));

   66     }

   67     //-----------------------------------------------------------------------------

   68     // 숫자에 3자리마다 , 를 찍어서 반환

   69     // @return : String

   70     //-----------------------------------------------------------------------------

   71     String.prototype.money = function() {

   72         var num = this.trim();

   73         while((/(-?[0-9]+)([0-9]{3})/).test(num)) {

   74             num = num.replace((/(-?[0-9]+)([0-9]{3})/), "$1,$2");

   75         }

   76         return num;

   77     }

   78     //-----------------------------------------------------------------------------

   79     // 숫자의 자리수(cnt)에 맞도록 반환

   80     // @return : String

   81     //-----------------------------------------------------------------------------

   82     String.prototype.digits = function(cnt) {

   83         var digit = "";

   84         if (this.length < cnt) {

   85             for(var i = 0; i < cnt - this.length; i++) {

   86                 digit += "0";

   87             }

   88         }

   89         return digit + this;

   90     }

   91     //-----------------------------------------------------------------------------

   92     // " -> &#34; ' -> &#39;로 바꾸어서 반환

   93     // @return : String

   94     //-----------------------------------------------------------------------------

   95     String.prototype.quota = function() {

   96         return this.replace(/"/g, "&#34;").replace(/'/g, "&#39;");

   97     }

   98     //-----------------------------------------------------------------------------

   99     // 파일 확장자만 가져오기

  100     // @return : String

  101     //-----------------------------------------------------------------------------

  102     String.prototype.ext = function() {

  103         return (this.indexOf(".") < 0) ? "" : this.substring(this.lastIndexOf(".") + 1, this.length);   

  104     }

  105     //-----------------------------------------------------------------------------

  106     // URL에서 파라메터 제거한 순수한 url 얻기

  107     // @return : String

  108     //-----------------------------------------------------------------------------   

  109     String.prototype.uri = function() {

  110         var arr = this.split("?");

  111         arr = arr[0].split("#");

  112         return arr[0];   

  113     }

  114 

  115 /*---------------------------------------------------------------------------------*\

  116  *  각종 체크 함수들

  117 \*---------------------------------------------------------------------------------*/

  118     //-----------------------------------------------------------------------------

  119     // 정규식에 쓰이는 특수문자를 찾아서 이스케이프 한다.

  120     // @return : String

  121     //-----------------------------------------------------------------------------

  122     String.prototype.meta = function() {

  123         var str = this;

  124         var result = ""

  125         for(var i = 0; i < str.length; i++) {

  126             if((/([\$\(\)\*\+\.\[\]\?\\\^\{\}\|]{1})/).test(str.charAt(i))) {

  127                 result += str.charAt(i).replace((/([\$\(\)\*\+\.\[\]\?\\\^\{\}\|]{1})/), "\\$1");

  128             }

  129             else {

  130                 result += str.charAt(i);

  131             }

  132         }

  133         return result;

  134     }

  135     //-----------------------------------------------------------------------------

  136     // 정규식에 쓰이는 특수문자를 찾아서 이스케이프 한다.

  137     // @return : String

  138     //-----------------------------------------------------------------------------

  139     String.prototype.remove = function(pattern) {

  140         return (pattern == null) ? this : eval("this.replace(/[" + pattern.meta() + "]/g, \"\")");

  141     }

  142     //-----------------------------------------------------------------------------

  143     // 최소 최대 길이인지 검증

  144     // str.isLength(min [,max])

  145     // @return : boolean

  146     //-----------------------------------------------------------------------------

  147     String.prototype.isLength = function() {

  148         var min = arguments[0];

  149         var max = arguments[1] ? arguments[1] : null;

  150         var success = true;

  151         if(this.length < min) {

  152             success = false;

  153         }

  154         if(max && this.length > max) {

  155             success = false;

  156         }

  157         return success;

  158     }

  159     //-----------------------------------------------------------------------------

  160     // 최소 최대 바이트인지 검증

  161     // str.isByteLength(min [,max])

  162     // @return : boolean

  163     //-----------------------------------------------------------------------------

  164     String.prototype.isByteLength = function() {

  165         var min = arguments[0];

  166         var max = arguments[1] ? arguments[1] : null;

  167         var success = true;

  168         if(this.byte() < min) {

  169             success = false;

  170         }

  171         if(max && this.byte() > max) {

  172             success = false;

  173         }

  174         return success;

  175     }

  176     //-----------------------------------------------------------------------------

  177     // 공백이나 널인지 확인

  178     // @return : boolean

  179     //-----------------------------------------------------------------------------

  180     String.prototype.isBlank = function() {

  181         var str = this.trim();

  182         for(var i = 0; i < str.length; i++) {

  183             if ((str.charAt(i) != "\t") && (str.charAt(i) != "\n") && (str.charAt(i)!="\r")) {

  184                 return false;

  185             }

  186         }

  187         return true;

  188     }

  189     //-----------------------------------------------------------------------------

  190     // 숫자로 구성되어 있는지 학인

  191     // arguments[0] : 허용할 문자셋

  192     // @return : boolean

  193     //-----------------------------------------------------------------------------

  194     String.prototype.isNum = function() {

  195         return (/^[0-9]+$/).test(this.remove(arguments[0])) ? true : false;

  196     }

  197     //-----------------------------------------------------------------------------

  198     // 영어만 허용 - arguments[0] : 추가 허용할 문자들

  199     // @return : boolean

  200     //-----------------------------------------------------------------------------

  201     String.prototype.isEng = function() {

  202         return (/^[a-zA-Z]+$/).test(this.remove(arguments[0])) ? true : false;

  203     }

  204     //-----------------------------------------------------------------------------

  205     // 숫자와 영어만 허용 - arguments[0] : 추가 허용할 문자들

  206     // @return : boolean

  207     //-----------------------------------------------------------------------------

  208     String.prototype.isEngNum = function() {

  209         return (/^[0-9a-zA-Z]+$/).test(this.remove(arguments[0])) ? true : false;

  210     }

  211     //-----------------------------------------------------------------------------

  212     // 숫자와 영어만 허용 - arguments[0] : 추가 허용할 문자들

  213     // @return : boolean

  214     //-----------------------------------------------------------------------------

  215     String.prototype.isNumEng = function() {

  216         return this.isEngNum(arguments[0]);

  217     }

  218     //-----------------------------------------------------------------------------

  219     // 아이디 체크 영어와 숫자만 체크 첫글자는 영어로 시작 - arguments[0] : 추가 허용할 문자들

  220     // @return : boolean

  221     //-----------------------------------------------------------------------------

  222     String.prototype.isUserid = function() {

  223         return (/^[a-zA-z]{1}[0-9a-zA-Z]+$/).test(this.remove(arguments[0])) ? true : false;

  224     }

  225     //-----------------------------------------------------------------------------

  226     // 한글 체크 - arguments[0] : 추가 허용할 문자들

  227     // @return : boolean

  228     //-----------------------------------------------------------------------------

  229     String.prototype.isKor = function() {

  230         return (/^[가-힣]+$/).test(this.remove(arguments[0])) ? true : false;

  231     }

  232     //-----------------------------------------------------------------------------

  233     // 주민번호 체크 - arguments[0] : 주민번호 구분자

  234     // XXXXXX-XXXXXXX

  235     // @return : boolean

  236     //-----------------------------------------------------------------------------

  237     String.prototype.isJumin = function() {

  238         var arg = arguments[0] ? arguments[0] : "";

  239         var jumin = eval("this.match(/[0-9]{2}[01]{1}[0-9]{1}[0123]{1}[0-9]{1}" + arg + "[1234]{1}[0-9]{6}$/)");

  240         if(jumin == null) {

  241             return false;

  242         }

  243         else {

  244             jumin = jumin.toString().num().toString();

  245         }

  246         // 생년월일 체크

  247         var birthYY = (parseInt(jumin.charAt(6)) == (1 ||2)) ? "19" : "20";

  248         birthYY += jumin.substr(0, 2);

  249         var birthMM = jumin.substr(2, 2) - 1;

  250         var birthDD = jumin.substr(4, 2);

  251         var birthDay = new Date(birthYY, birthMM, birthDD);

  252         if(birthDay.getYear() % 100 != jumin.substr(0,2) || birthDay.getMonth() != birthMM || birthDay.getDate() != birthDD) {

  253             return false;

  254         }       

  255         var sum = 0;

  256         var num = [2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5]

  257         var last = parseInt(jumin.charAt(12));

  258         for(var i = 0; i < 12; i++) {

  259             sum += parseInt(jumin.charAt(i)) * num[i];

  260         }

  261         return ((11 - sum % 11) % 10 == last) ? true : false;

  262     }

  263     //-----------------------------------------------------------------------------

  264     // 외국인 등록번호 체크 - arguments[0] : 등록번호 구분자

  265     // XXXXXX-XXXXXXX

  266     // @return : boolean

  267     //-----------------------------------------------------------------------------

  268     String.prototype.isForeign = function() {

  269         var arg = arguments[0] ? arguments[0] : "";

  270         var jumin = eval("this.match(/[0-9]{2}[01]{1}[0-9]{1}[0123]{1}[0-9]{1}" + arg + "[5678]{1}[0-9]{1}[02468]{1}[0-9]{2}[6789]{1}[0-9]{1}$/)");

  271         if(jumin == null) {

  272             return false;

  273         }

  274         else {

  275             jumin = jumin.toString().num().toString();

  276         }

  277         // 생년월일 체크

  278         var birthYY = (parseInt(jumin.charAt(6)) == (5 || 6)) ? "19" : "20";

  279         birthYY += jumin.substr(0, 2);

  280         var birthMM = jumin.substr(2, 2) - 1;

  281         var birthDD = jumin.substr(4, 2);

  282         var birthDay = new Date(birthYY, birthMM, birthDD);

  283         if(birthDay.getYear() % 100 != jumin.substr(0,2) || birthDay.getMonth() != birthMM || birthDay.getDate() != birthDD) {

  284             return false;

  285         }

  286         if((parseInt(jumin.charAt(7)) * 10 + parseInt(jumin.charAt(8))) % 2 != 0) {

  287             return false;

  288         }

  289         var sum = 0;

  290         var num = [2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5]

  291         var last = parseInt(jumin.charAt(12));

  292         for(var i = 0; i < 12; i++) {

  293             sum += parseInt(jumin.charAt(i)) * num[i];

  294         }

  295         return (((11 - sum % 11) % 10) + 2 == last) ? true : false;

  296     }   

  297     //-----------------------------------------------------------------------------

  298     // 사업자번호 체크 - arguments[0] : 등록번호 구분자

  299     // XX-XXX-XXXXX

  300     // @return : boolean

  301     //-----------------------------------------------------------------------------

  302     String.prototype.isBiznum = function() {

  303         var arg = arguments[0] ? arguments[0] : "";

  304         var biznum = eval("this.match(/[0-9]{3}" + arg + "[0-9]{2}" + arg + "[0-9]{5}$/)");

  305         if(biznum == null) {

  306             return false;

  307         }

  308         else {

  309             biznum = biznum.toString().num().toString();

  310         }

  311         var sum = parseInt(biznum.charAt(0));

  312         var num = [0, 3, 7, 1, 3, 7, 1, 3];

  313         for(var i = 1; i < 8; i++) sum += (parseInt(biznum.charAt(i)) * num[i]) % 10;

  314         sum += Math.floor(parseInt(parseInt(biznum.charAt(8))) * 5 / 10);

  315         sum += (parseInt(biznum.charAt(8)) * 5) % 10 + parseInt(biznum.charAt(9));

  316         return (sum % 10 == 0) ? true : false;

  317     }

  318     //-----------------------------------------------------------------------------

  319     // 법인 등록번호 체크 - arguments[0] : 등록번호 구분자

  320     // XXXXXX-XXXXXXX

  321     // @return : boolean

  322     //-----------------------------------------------------------------------------

  323     String.prototype.isCorpnum = function() {

  324         var arg = arguments[0] ? arguments[0] : "";

  325         var corpnum = eval("this.match(/[0-9]{6}" + arg + "[0-9]{7}$/)");

  326         if(corpnum == null) {

  327             return false;

  328         }

  329         else {

  330             corpnum = corpnum.toString().num().toString();

  331         }

  332         var sum = 0;

  333         var num = [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]

  334         var last = parseInt(corpnum.charAt(12));

  335         for(var i = 0; i < 12; i++) {

  336             sum += parseInt(corpnum.charAt(i)) * num[i];

  337         }

  338         return ((10 - sum % 10) % 10 == last) ? true : false;

  339     }

  340     //-----------------------------------------------------------------------------

  341     // 이메일의 유효성을 체크

  342     // @return : boolean

  343     //-----------------------------------------------------------------------------

  344     String.prototype.isEmail = function() {

  345         return (/\w+([-+.]\w+)*@\w+([-.]\w+)*\.[a-zA-Z]{2,4}$/).test(this.trim());

  346     }

  347     //-----------------------------------------------------------------------------

  348     // 전화번호 체크 - arguments[0] : 전화번호 구분자

  349     // @return : boolean

  350     //-----------------------------------------------------------------------------

  351     String.prototype.isPhone = function() {

  352         var arg = arguments[0] ? arguments[0] : "";

  353         return eval("(/(02|0[3-9]{1}[0-9]{1})" + arg + "[1-9]{1}[0-9]{2,3}" + arg + "[0-9]{4}$/).test(this)");

  354     }

  355     //-----------------------------------------------------------------------------

  356     // 핸드폰번호 체크 - arguments[0] : 핸드폰 구분자

  357     // @return : boolean

  358     //-----------------------------------------------------------------------------

  359     String.prototype.isMobile = function() {

  360         var arg = arguments[0] ? arguments[0] : "";

  361         return eval("(/01[016789]" + arg + "[1-9]{1}[0-9]{2,3}" + arg + "[0-9]{4}$/).test(this)");

  362     }

출처 http://www.zzbb.kr/24


posted by 준치 2008. 10. 13. 16:21
// 오른마우스 금지, 나중에 해당 주석 풀고 사용
function rightbutton(e)
{
 if (navigator.appName == 'Netscape' && (e.which == 3 || e.which == 2))
 return false;
 else if (navigator.appName == 'Microsoft Internet Explorer' && (event.button == 2 || event.button == 3))
 {
  alert("죄송합니다!! 정보무단복제를 막기 위하여 오른쪽 마우스 사용을 허용하지 않습니다.");
  return false;
 }
  return true;
}
//document.onmousedown=rightbutton; // 컨트롤 키 금지, 나중에 해당 주석 풀고 사용
posted by 준치 2008. 9. 29. 15:54

javascript parseInt 는 원래 parseInt(string, radix) 로 주어야 된다.
radix 를 주지 않으면 자동으로 찾아낼려고 시도를 하는데,

1-9 로 시작하면 10진법
0x 로 시작하면 16진법
0 으로 시작하면 8진법으로 이해한다.

8진법에서는 08, 09 가 없기 때문에.

parseInt("08") 을 하면 0이 나오게 된다.

posted by 준치 2008. 9. 25. 19:41

음...쇼핑몰에 마우스 움직일때 Banner가 같이 움직인다..많이 있다는데 그래도 같이 알면 좋잖아여..ㅎㅎ

웹페이지에서 div로 감싸서 사용해야하고 밑에 소스는 오픈될때부터 호출하면 된다...ㅎㅎㅎ
<div id="divMenu" style="right: 0%; WIDTH:210px; position: absolute; HEIGHT:172px">
움직일 테이블
</div>

var bNetscape4plus = (navigator.appName == "Netscape" && navigator.appVersion.substring(0,1) >= "4");
var bExplorer4plus = (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.substring(0,1) >= "4");

var topValue = 18;
var startBannerValue = topValue + 80;

function MoveElements()
{
 var yMenuFrom, yMenuTo, yButtonFrom, yButtonTo, yOffset, timeoutNextCheck;

 if ( bNetscape4plus )
 {
  yMenuFrom   = document["divMenu"].top;
  yMenuTo     = top.pageYOffset + topValue;   //배너의 top 위치 지정
 }
 else if ( bExplorer4plus )
 {
  yMenuFrom   = parseInt (divMenu.style.top, 10);
  yMenuTo     = document.body.scrollTop + topValue; //배너의 top 위치 지정
 }

 timeoutNextCheck = 100;

 if ( Math.abs (yButtonFrom - (yMenuTo + 152)) < 6 && yButtonTo < yButtonFrom )
 {
  setTimeout ("MoveElements()", timeoutNextCheck);
  return;
 }


 if ( yButtonFrom != yButtonTo )
 {
  yOffset = Math.ceil( Math.abs( yButtonTo - yButtonFrom ) / 10 );
  if ( yButtonTo < yButtonFrom )
          yOffset = -yOffset;

  if ( bNetscape4plus )
          document["divLinkButton"].top += yOffset;
  else if ( bExplorer4plus )
          divLinkButton.style.top = parseInt (divLinkButton.style.top, 10) + yOffset;

  timeoutNextCheck = 10;
 }
 if ( yMenuFrom != yMenuTo )
 {
  yOffset = Math.ceil( Math.abs( yMenuTo - yMenuFrom ) / 20 );
  if ( yMenuTo < yMenuFrom )
          yOffset = -yOffset;

  if ( bNetscape4plus )
          document["divMenu"].top += yOffset;
  else if ( bExplorer4plus )
          divMenu.style.top = parseInt (divMenu.style.top, 10) + yOffset;

  timeoutNextCheck = 10;
 }

 setTimeout ("MoveElements()", timeoutNextCheck);
}

function StartBanner()
 {
  var y;
 
  if( bNetscape4plus )
  {
   document["divMenu"].top = top.pageYOffset + startBannerValue;
   document["divMenu"].visibility = "visible";
  }
  else if( bExplorer4plus )
  {
   divMenu.style.top = document.body.scrollTop + startBannerValue;
   divMenu.style.visibility = "visible";
  }

  MoveElements();
  return true;
 }

posted by 준치 2008. 9. 25. 15:10
찾다보니 나와서 올려..slice(시작,끝) 이렇게 사용하네..간단 예제...

<script type="text/javascript">
    var str="abcdef";
    alert(str.slice(2,4));
</script>

결과 cd 이렇게 나온다.
posted by 준치 2008. 9. 20. 16:55

현재 까지 써본것은 escape 와 unescape 함수인데 다른 값으로 변경되는 경우가 있어서
다른것은 테스트 해보려한다..ㅎㅎㅎ

* encodeURI() : decodeURI()
* encodeURIComponent() : decodeURIComponent()
* escape() : unescape()

테스트 결과 sharepoint SearchServer에서는 encodeURI 이 함수를 쓴다
밑에 소스 str에 원하는 한글을 넣으면 된다..ㅎㅎㅎ

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
 </HEAD>
 <script language="javascript">
 function change(str)
 {
document.write("-----encodeURI </br>");
document.write(encodeURI(str));
document.write("</br>");
document.write("-----decodeURI </br>");
document.write(decodeURI(str));
document.write("</br>");
document.write("----encodeURIComponent </br>");
document.write(encodeURIComponent(str));
document.write("</br>");
document.write("----decodeURIComponent </br>");
document.write(decodeURIComponent(str));
document.write("</br>");
document.write("----escape </br>");
document.write(escape(str));
document.write("</br>");
document.write("----unescape </br>");
document.write(unescape(str));

}
 </script>
 <BODY>
  <input type="button" value="button" onclick="change('인사')">
 </BODY>
</HTML>

posted by 준치 2008. 9. 12. 01:48

현재 url을 가져오기 간단하지만 자꾸 잊어서 올려요..ㅎㅎ

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
  <script>
function url()
{
 alert(document.location.href);   //요기 ㅋㅋㅋ
}
  </script>
 </HEAD>

 <BODY>
  <input type="button" text="button" onclick="url()">
 </BODY>
</HTML>