개발자의 길

자바스크립트 - location 객체와 String 객체 본문

2. JS

자바스크립트 - location 객체와 String 객체

자르르 2010. 1. 21. 15:19


[ location 객체 ]

 

웹 브라우저의 주소 입력줄에 입력된 주소 값을 관리하는 location 객체는 주로 지정한 문서로 이동할 때 사용한다.

location 객체는 웹 브라우저의 주소 입력줄에 입력되는 주소 정보를 관리한다.

보통 http://www.hanbitbook.co.kr 로 접속하는 경우 완전한 주소 값

http://www.hanbitbook.co.kr:8080/main/index.html  로 아래와 같이 세분화할 수 있다.

-------------------- 세분화 ----------------------
http://www.hanbitbook.co.kr:8080/main/index.html #2

http://www.hanbitbook.co.kr:8080/main/index.html #2 --> href

//www --> protocal

hanbitbook.co.kr:8080 ---> host

hanbitbook.co.kr ---> hostname

8080 ----> port

main/index.html ---> pathname

#2 ----> hash

---------------------------------------------

------- 사용형식 --------

windows.location.속성

location.속성 = 값

location.메소드

---------------------------------------------


-------------------- location 객체의 속성 ----------------------

○ has
    - # 다음에 오는 문자열, 즉 앵커 이름을 표시

○ host
    - 호스트명과 포트번호 표시

○ hostname
    - 호스트명을 표시

○ href
    - 완전한 형태의 URL 주소 표시

○ pathname
    - 문서의 경로 표시

○ port
    - 포트번호 표시

○ protocol
    - 프로토콜 종류 표시

○ serch
    - 검색 엔진을 실행할 때 나타나는 ? 이후의 문자 표시

----------------------------------------------------------------


-------------------- location 객체의 메소드 ----------------------

○ reload()
    - 문서를 다시 읽어옴(새로 고침)

○ replace("URL 주소")
    - 문서를 URL 즈소로 대체하고 이전 페이지로 돌아갈 수 없게 설정 (넷스케이프 전용)

----------------------------------------------------------------

 

[실습하기]

 

------------------ 주소 입력줄 삽입하기 ----------------------
<html>

<head>
<title>Test</title>

<script language=javascript>

function Go(ListBox)
{
 if(ListBox.selectedIndex != 0)
 document.location.href = ListBox.value
/*
 if(ListBox.selectedIndex !=0)
 location=ListBox.options(listBox.selectedIndex).value;
*/

</script>

</head>

<body>

<form name=info>
<select name=url onChange="Go(this)">
 <option selected>선택하세요.</option>
 <option value=http://www.naver.com>네이버</option>
 <option value=http://www.daum.net>다음</option>
 <option value=http://www.yahoo.co.kr>야후</option>
 <option value=http://blog.naver.com/kimgudtjr>형석이블로그</option>
</select>
&nbsp;&nbsp;
<input type=text name=site size=35 value=http://www.>
<input type=button name=bt value="이동" onClick="location.href=document.info.site.value">

</form>


</body>

</html>
------------------------------------------------------------------

 

====================================================================================


[ string 객체 ]

 

string 객체는 문자열에서 원하는 문자열을 찾거나 문자의 개수를 알아내는 등 다양한 일을 한다.

string 객체의 경우 회원가입 양식과 같이 사용자에게 입력받은 문자열을 처리할 때 많이 활용하므로

예제를 통해서 익히고 다양하게 접근해 보도록 한다.

string 객체는 문자열을 객체로 만들어주므로, 문자열 개게초 글자의 속성이나 하이퍼링크 등을 설정 할 수 있다.

string은 Date() 객체처럼 new 연산자를 사용하지 않고 변수에 대입시킨 다음 변수와 속성, 메소드를 마침표(.)로 연결하여

문자열 처리 한다.

------------형식)----------------
변수 = "문자열"
변수.속성
변수.메소드
---------------------------------

string 객체는 length 속성을 갖으며 , length 속성은 문자열의 개수를 계산해준다.

예를들어 '환영합니다' 의 length 속성 값은 5, '환영 인사' 의 속성 값도 5다. 영문, 한글, 공백 모두 한 글자로 계산된다.

"문자열"length

=====문자를 꾸며주는 메소드=====
string 객체의 메소드 중에서 문자를 꾸며주는 메소드는 다음처럼 사용한다.
 "환영합니다.".bold()
 "환영합니다.".bold() .fontcolor("red")

문자열 객체에서 사용되는 글자 속성 관련 메소드는 다음과 같ㄷ.

-------------- 문자열 객체에서 사용되는 글자 속성 관련 메소드 --------------------------

○ big()
    - <big> 태그와 같이 글자크기를 크게 설정

○ small()
    - <small> 태그와 같이 글자크기를 작게 설정

○ fontsize(숫자)
    - <font 태그처럼 글자크기를 지정

○ fontcolor("색상명")
    - 글자색 지정

○ bold()
    - <bold> 태그와 같이 글자를 진하게 설정

○ fixed()
    - <tr> 태그와 같이 글자크기를 고정시킴

○ italic()
    - <i> 태그와 같이 글자를 이탤릭체로 설정

○ strike()
    - <strike> 태그와 같이 취소선을 설정

○ sup()
    - <sup> 태그와 같이 글자를 위첨자로 설정

○ sub()
    - <sub> 태그와 같이 글자를 아래첨자로 설정

○ blink()
    - <blink> 태그와 같이 글자가 깜박이도록 설정(넷스케이프 전용)


------------------------------------------------------------------------------------------

=====하이퍼링크를 설정하는 메소드=====

string 객체의 메소드 중에서 문자에 하이퍼링크를 설정하는 메소드는 다음과 같다.

1. link() 메소드는 문자열 객체에 하이퍼링크를 설정한다. <a href="URL 주소"> 와 같다.
    형식) "문자열".link("URL 주소")

2.anchor() 메소드는 책갈피 위치를 지정하여 문서의 특정 위치로 이동하게 한다. <a name="책갈피명">과 같다.
    형식) "문자열".anchor("책갈피명")
            "문자열".link("#책갈피명")

-------------------------------------------------------------------------------------------
===== 문자열 처리 메소드 =====

"환영합니다.".indexof("합")
"환영합니다.".subsrt(2,4)
"환영합니다.".toUpperCase()


------------------------- 문자열 객체의 정보를 가져오는 메소드 ----------------

----------------------- 문자열 위치와 관련된 메소드 ------------------------
○ indexOf("문자")
   - 문자열 객체 중에서 문자의 위치 값을 왼쪽부터 계산하여 숫자로 표시한다. 시작은 0부터 없으면 -1이 된다.

○ indexOf("문자",n)
   - 문자를 문자열의  n번째 문자부터 찾는다.

○ lastIndexOf("문자",n)
   - 문자열 객체 중에서 문자의 위치를 오른쪽부터 계산하여 숫자로 표시한다. 시작은 0부터 업으면 -1

○ charAt(n)
   - 문자열에서 n번째 위치한 문자를 찾아준다 숫자는 0번부터 시작한다.

---------------------------------------------------------------


----------------------- 문자열에 포함된 문자 표시 방법 ------------------------

○ substring(n,m)
   - 문자열의 n번째 문자부터 m번째 문자까지 표시한다. 음수 값은 무시된다.

○ slice(n,m)
   - substring과 동일하고, 음수 값은 오른쪽부터 순번으로 계산된다.

○ substr(n,m)
   - 문자열의 n번째 문자부터 m개의 문자를 표시한다.
---------------------------------------------------------------


----------------------- 문자열 분리와 결합 ------------------------

○ split("구분문자")
   - 구분문자를 이용해서 문자열 객체를 분리시킨다.

○ concat("문자열")
   - 문자열을 문자열 객체에 결합시킨다.
---------------------------------------------------------------


----------------------- 대소문자 구분------------------------

○ toUpperCase()
   - 모두 대문자로 표시한다.

○ toLowerCase()
   - 모두 소문자로 표시한다.

---------------------------------------------------------------


--------------------- 기타 -----------------------

○ eval()
   - 문자열을 수치로 바꾼다.


○ toString(n)
   - 수치를 n진수로 바꾸어 표시한다.


○ match()
   - 지정한 문자와 동일한 패턴을 찾는다. 없으면 널 값을 반환한다.


○ search()
   - 문자열에서 지정한 문자 턴을 찾아 그 패턴의 오프셋 값(정수)를 반환한다.


○ replace()
   - 지정한 문자를 찾아 지정한 다른 문자열로 바꾼다.


○ CharCodeAt(n)
   - 문자열의 n번째 문자를 ISO-Latin-1 코드 값으로 표시한다.

------------------------------------------------------------

========================================================================================


[실습하기]

--------------- 입력한 이메일 주소 형식 확인하기 -----------------------------
<html>

<head>
<title>Test</title>

<script language=javascript>

function check()
{
 var emailvalue = document.info.email.value

 if(emailvalue.indexOf("@") == -1)
 {
  alert("입력된 이메일이 잘못되었습니다.");
 }
 else
 {
  alert("입력된 이메일로 가입이 되었습니다.");
 }

}

</script>

</head>

<body>

<form name=info>
 <input type=text name=email size=30>
 <input type=button value=가입 onclick="check()">
</form>

메일서비스에 가입할 이메일주소를 입력하세요<br>
'@' 가 있어야함.

</body>

</html>
-------------------------------------------------------------------------------------------


----------------- 아이디 입력상자에 영문과 숫자만 되도록 하기 ----------------------
<html>

<head>
<title>Test</title>

<script language=javascript>

function check()
{
 var str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
 var idstr = document.info.id.value;
 var lened = idstr.length;
 var checked = 0;

 for(i=0; i<lened; i++)
 {
  checked = str.indexOf(idstr.charAt(i))
  if(checked == -1) break;
 }

 if(checked == -1)
 {
  alert("입력하신 아이디가 올바르지 않습니다.");
 }
 else
 {
  alert("로그인 성공");
 }


 
 
}

</script>

</head>

<body>

<form name=info>
 <input type=text name=id size=30>
 <input type=button value=로그인 onclick="check()">
</form>

영문과 숫자만 입력하세요

</body>

</html>
-----------------------------------------------------------------------------------

 

------------------- string 객체 사용 -----------------------------------------
<html>
<head>
<title>string객체</title>

<script language=javascript>

var m="21C 한빛(Hanbit Media)에 오신것을 환영합니다."   //문자열변수선언, string객체 생성
//document.write("<h3 style='line-height:23pt;'>") 
//***********************************************************목차
document.write("목차".anchor("top") + "<BR>")
document.write("글자를 꾸며주는 문자열 객체".link("#flag1") + "<BR>")
document.write("글자 정보를 표시하는 문자열 객체".link("#flag2") + "<BR>")

document.write(m.length + "<br>")  //문자열길이


//***********************************************************책갈피1
document.write("<hr>글자를 꾸며주는 문자열 객체".anchor("flag1") + "<BR>")

document.write(" big ".big() + "<br>")
document.write(" small ".small() + "<br>")
document.write(" blink ".blink() + "<br>") //깜빡이게, nc에서만 지원됨.
document.write(" bold ".bold() + "<br>")
document.write(" fix ".fixed() + "<br>")
document.write(" italics ".italics() + "<br>")
document.write(" strike ".strike() + "<br>")
document.write(" subscript ".sub() + "<br>")
document.write(" superscript ".sup() + "<br>")
document.write(" fontcolor = green ".fontcolor("green") + "<br>")
document.write(" fontcolor = blue ".fontcolor("blue") + "<br>")
document.write(" fontcolor = red ".fontcolor("red") + "<br>")
document.write(" font size 3 ".fontsize(3) + "<br>")
document.write(" font size 4 ".fontsize(4) + "<br>")
document.write(" font size 5 ".fontsize(5) + "<br>")

document.write("font size 3,bold".fontsize(3).bold()+"<br>")
document.write("font size 5,strike,red".fontsize(5).strike().fontcolor("red")+"<br>")
document.write(m.fontsize(5).blink().bold().fontcolor("green")+"<br>")


//***********************************************************책갈피2
document.write("<hr>글자 정보를 표시하는 문자열 객체".anchor("flag2") + "<BR>")

document.write(m.toUpperCase() + '<br>') 
document.write(m.toLowerCase() + '<br>') 

document.write(m.charAt(5) + '<br>')  
document.write(m.substring(0,4) + '<br>')

document.write(m.indexOf('h') + '<br>')
document.write(m.lastIndexOf('h') + '<br>')

document.write("네이버".link("http://www.naver.com") + "<BR>")
document.write("다음넷".link("http://www.daum.net") + "<P>")


//***********************************************************책갈피3
document.write("위로..".link("#top") + "<BR>")

</script>
</head>


<body>

</body>
</html>



이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.
공유하기 링크
Comments