javascript에서 왼쪽과 오른쪽 공백을 없애는 trim을 정규식으로 구현할 수 있다.

소스>

 String.prototype.trim = function()
 {
   return this.replace(/^\s+|\s+$/g, "");
 }

 

jQuery 사용 예>

$('#name').val($('#name').val().trim());

 

javascript 사용 예>

document.getElementById('name').value = document.getElementById('name').value.trim();

 

사용 예>

 <form name="f" method="post" action="폼 전송 주소">
 <input type="text" id="name" name="name" maxlength="4" />
 <input type="button" value="확인" onclick="btnSubmit()" />
 </form>
 <script type="text/javascript">
 <!--
 // 정규식 : trim()
 String.prototype.trim = function()
 {
   return this.replace(/^\s+|\s+$/g, "");
 }


 // 폼 전송
 function btnSubmit()
 {
  // 확인 : 이름
  $('#name').val($('#name').val().trim());

  //document.f.submit();
 }
 //--> 

Posted by 은둔고수

자바스크립트를 이용해서 현재 접속해 있는 사이트의 도메인을 알아내기

소스>

function rtnDomainName(url)
{
 url = url.split('//');
 url = url[1].substr(0,url[1].indexOf('/'));

 return url;
}

var url = location.href;
alert(rtnDomainName(url));

 

결과>

okkk.tistory.com

Posted by 은둔고수

현재 페이지(접속해 있는)의 주소(URL)를 javascript로 알아내기

location.href 또는 document.location.href

 

사용 예>

<script tyle="text/javascript">

<!--

alert(location.href)

//-->

</script>

Posted by 은둔고수

익스플로러(explorer)에서는 location.href가 실행이되는데

파이어폭스(ff : firefox)에서 반응이 없다.

이럴땐 location.replace를 사용한다.

예>수정 전 :

<select name="urlChange" onchange="location.href('http://okkks.tistory.com/');">

  <option name="okkks.tistory.com" value="http://okkks.tistory.com">http://okkks.tistory.com</option>

</select>

수정 후 : <select name="urlChange" onchange="location.replace('http://okkks.tistory.com/');">

Posted by 은둔고수


<script type="text/javascript">
<!--
/*------------------------------------------------------------------------------------------
// 화면 로드 후 처리
------------------------------------------------------------------------------------------*/
window.onload = function()
{
 // div height 설정
 setDivHeight('div_left','div_content');
}


/*------------------------------------------------------------------------------------------
// div height 설정
// objSet : 변경할 div id
// objTar : height값을 구할 대상 div id
------------------------------------------------------------------------------------------*/
function setDivHeight(objSet, objTar)
{
  var objSet   = document.getElementById(objSet);
  var objTarHeight= document.getElementById(objTar).offsetHeight;
  objSet.style.height  = objTarHeight + "px";
}
//-->
</script>

<div>
  <div id="div_left"></div>
  <div id="div_content"></div>
</div>

설명>div_content div의 내용에 따라 height 크기가 변경되면 왼쪽에 있는 div_left div height 크기도 자동으로 변경된다. 

Posted by 은둔고수


[스크롤 위치 알아내기]

# 스크롤 상단 위치값
document.body.scrollTop

# 스크롤 왼쪽 위치값
document.body.scrollLeft
 
[문제점]
HTML 코드 상당엔 DTD 가 선언되어 있다면 scrollTop으로는 값을 알아내지 못하는
문제가 발생된다.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

[해결책]
document.documentElement.scrollTop
또는, document.html.scrollTop

ie(익스플로어)의 경우 XHTML로 넘어오면서 호환에서 표준모드로 변경되면서 발생된
것으로 보인다.

Posted by 은둔고수

아스키 코드표
 

0 NULL 32 [space] 64 @ 96 `
1 SOH 33 ! 65 A 97 a
2 STX 34 " 66 B 98 b
3 ETX 35 # 67 C 99 c
4 EOT 36 $ 68 D 100 d
5 ENQ 37 % 69 E 101 e
6 ACK 38 & 70 F 102 f
7 BEL 39 ' 71 G 103 g
8 * * 40 ( 72 H 104 h
9 [TAB] 41 ) 73 I 105 i
10 [Line Feed] 42 * 74 J 106 j
11 VT 43 + 75 K 107 k
12 FF 44 , 76 L 108 l
13 CR 45 - 77 M 109 m
14 SO 46 . 78 N 110 n
15 SI 47 / 79 O 111 o
16 DLE 48 0 80 P 112 p
17 DC1 49 1 81 Q 113 q
18 SC2 50 2 82 R 114 r
19 SC3 51 3 83 S 115 s
20 SC4 52 4 84 T 116 t
21 NAK 53 5 85 U 117 u
22 SYN 54 6 86 V 118 v
23 ETB 55 7 87 W 119 w
24 CAN 56 8 88 X 120 x
25 EM 57 9 89 Y 121 y
26 SUB 58 : 90 Z 122 z
27 ESC 59 ; 91 [ 123 {
28 FS 60 < 92 \ 124 |
29 GS 61 = 93 ] 125 }
30 RS 62 > 94 ^ 126 ~
31 US 63 ? 95 _ 127 DEL

Posted by 은둔고수

[javascript-tip][ie7,ff3]javascript를 이용한 글자 수 알아내기(byte)-입력시 바로 알아내기(timer 이용)

 

 

<script language="javascript">
<!--
var timerBytes;


/*----------------------------------------------------------------------------------------
// 타이머 없애기
----------------------------------------------------------------------------------------*/
function clearTimerStrBytes()
{
 clearTimeout(timerBytes);
}


/*----------------------------------------------------------------------------------------
// 계산 : 글자 수(타이머를 이용한 byte 방식)
----------------------------------------------------------------------------------------*/
function setTimerStrBytes(objThis,eid)
{
 if(document.getElementById(objThis.id) == null)
 {
  return;
 }
 
 var str = document.getElementById(objThis.id).value;
 var l = 0;

 for(var i=0, c; i<str.length; i++)
 {
  c=str.charCodeAt(i);

  if(c > 128 )
  {
   l +=  2;
  }
  
  else
  {
   l +=  1;
  }
 }

 document.getElementById(eid.id).innerHTML = l;

 var fn = function()
 {
   setTimerStrBytes(objThis,eid);
 }

 timerBytes = setTimeout(fn,100);
}
//-->
</script>


<table width="300" height="40" border="0" cellpadding="0" cellspacing="0">
<tr height="10">
 <td></td>
</tr>
<tr>
 <td><font color="#6e75c1">입력 글자 수 : <font style="font-size:11px">(<span id="divStrLength" name="divStrLength">0</span>/255)</font></font></td>
</tr>
<tr>
 <td><input type="text" id="tareaMemo" name="tareaMemo" onfocus="setTimerStrBytes(document.getElementById('tareaMemo'),document.getElementById('divStrLength'));" onblur="clearTimerStrBytes();" onkeypress="if(event.keyCode==13){clearTimerStrBytes();}" style="width:250px; height:20px; border:1px solid #a5aded"></td>
</tr>
</table>

Posted by 은둔고수

[javascript-tip]문자열 앞뒤 공백을 없애는 자바스크립트 함수(trim()함수)

 

[1번째 방법]
function jstrim(s)

{
  while (s.charAt(0) == " ")

  {
    s = s.substr(1);
  }

 

  while (s.charAt(s.length-1) == " ")

  {
    s = s.substr(0, s.length-1);
  }

  return s;

}

 

 

[2번째 방법]
function trim (strSource)

{
  re = /^s+|s+$/g;

  return strSource.replace(re, '');
}

 

function ltrim (strSource)

{
  re = /^s+/g;

  return strSource.replace(re, '');
}

 

function rtrim (strSource)

{
  re = /s+$/g;

  return strSource.replace(re, '');
}

 

 

[3번째 방법]
String.prototype.trim=function()
{
  var str=this.replace(/(\s+$)/g,"");
  return str.replace(/(^\s*)/g,"");
}

 

예>
a=" assdf asdf ";
alert(a.trim());


 

 

[4번째 방법]
function trim(str)
{
  return str.replace(/^\s+|\s+$/, '');
}

a=" assdf asdf ";
alert(a.trim());

 

 


[5번째 방법]
String.prototype.trim = function()
{
  // 좌우공백제거
  return this.replace(/^\s+|\s+$/g, "");
}

 

 

function fncCheckAll()
{
  var a = " a b c ";
  alert("a :" + a);

  var b = a.trim();
  alert("b :" + b);

  return;
}

Posted by 은둔고수

[javascript-tip]문자열(한글 2바이트 1글자로 인식) 길이 체크

 

한글 2Byte를 1글자로 인식하는 javascript 예제입니다.

 

 

<html>
 <head>
  <title>[javascript-tip]문자열(한글 2바이트 1글자로 인식) 길이 체크</title>
 </head>
 <script language="JavaScript">
  <!--
  function check()
  {
   var string = document.a.test.value;
   alert(getStringLength(string));
  }

 

  // 문자열 길이 체크 알파뉴메릭(1자리), 한글(2자리)
  function getStringLength (str)
  {
   var retCode = 0;
   var strLength = 0;

   for (i = 0; i < str.length; i++)
   {
    var code = str.charCodeAt(i)
    var ch = str.substr(i,1).toUpperCase()

    code = parseInt(code)

    if ((ch < "0" || ch > "9") && (ch < "A" || ch > "Z") && ((code > 255) || (code < 0)))
     strLength = strLength + 2;
    else
     strLength = strLength + 1;
   }
   return strLength;
  }
  //-->
 </script>
</head>
<body>
 <form name="a">
  <input type="text" name="test"><input type="button" value="체크" onClick="JavaScript:check();">
 </form>
</body>
</html>

Posted by 은둔고수