일반 Javascript 내장객체 String

황제낙엽 2007.04.10 16:43 조회 수 : 392 추천:139

sitelink1 http://cafe.naver.com/brdesign.cafe?ifra...icleid=528 
sitelink2 http://www.w3schools.com/jsref/jsref_obj_string.asp 
sitelink3  
sitelink4  
extra_vars4  
extra_vars5  
extra_vars6  
Javascript 내장객체  String

자바스크립트에서 문자열은 한개 이상의 문자로 구성된 것을 의미합니다.
"abcd"는 각각 a,b,c,d의 문자들로 구성된 집합인 것입니다.
이러한 집합을 문자열이라고 하며, 문자열은 따옴표('')나 쌍따옴표("")로 묶어서 나타냅니다.
예를 들어 10은 숫자지만, "10"은 1과 0으로 구성된 문자열이 되는 것입니다.
또한, "a"와 같이 하나의 문자도 따옴표로 묶어주면 문자열이 됩니다.
일반적으로 자바스크립트에서 사용되는 문자열이 String 객체입니다.

<HTML>
<HEAD>
<TITLE>String 예제</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
var str="핸드폰";
var len=str.length;
document.write("문자의 수는 "+len+"입니다.");
//-->
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>

< 실행결과 > 문자의 수는 3입니다.

 

결과로 3을 반환합니다. 앞에서도 언급했지만 영어는 1byte이고 한글은 2byte입니다.
지금은 문자의 갯수를 나타내지만 한글을 byte로 계산하여 2byte로 인식하면, 결과는 6으로 표시가 될 것입니다.

또한, 자바스크립트 String객체에서는 HTML 태그를 대신할 수 있는 메소드를 제공합니다.

 

메소드 설명
anchor("라벨") <a name="라벨"></a> : HTML 앵커를 생성
link("경로") <a href="경로"></a> : HTML의 하이퍼링크 생성
big() <big>~</big> : <big>태그를 사용한 것과 같은 결과를 출력
small() <small>~</small> : <small>태그를 사용한 것과 같은 결과를 출력
blink() <blink>~</blink> : <blink>태그를 사용한 것과 같이 깜박거리는 문자열 출력
bold() <b>~</b> : <b>태그를 사용한 것과 같이 문자열을 볼드체로 출력
italics() <i>~</i> <i>태그를 사용한 것과 같이 문자열을 이텔릭체로 출력
fontcolor("색") <font color="색"></font> : 문자열의 색을 설정
fontsize("크기") <font size="크기"></font> : 문자열의 크기를 설정
fixed() <tt>~</tt> : <tt>태그처럼 문자열이 고정된 높이를 갖도록 출력
strike() <strike>~</strike> : <strike>태그를 사용한 것과 같이 문자열의 중앙에 선을 출력
sub() <sub>~</sub> : <sub>태그를 사용한 것과 같이 문자열을 아래첨자 형태로 출력
sup() <sup>~</sup> : <sup>태그를 사용한 것과 같이 문자열을 윗 첨자 형태로 출력


다음의 예제로 확인합니다.

<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
var str="핸드폰";
document.write(str.anchor("name01")+"<br>");
document.write(str.link("http://www.ddcom.co.kr")+"<br>");
document.write(str.big()+"<br>");
document.write(str.small()+"<br>");
document.write(str.blink()+"<br>");
document.write(str.bold()+"<br>");
document.write(str.italics()+"<br>");
document.write(str.fontcolor("red")+"<br>");
document.write(str.fontsize("5")+"<br>");
document.write(str.fixed()+"<br>");
document.write(str.strike()+"<br>");
document.write(str.sub()+"<br>");
document.write(str.sup()+"<br>");

//-->
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>



< 실행결과 >
핸드폰
핸드폰
핸드폰
핸드폰
핸드폰
핸드폰
핸드폰
핸드폰
핸드폰
핸드폰
핸드폰
핸드폰
핸드폰

결과를 Internet Explorer에서 확인한다면, blink()로 설정된 문자열은 설정이 적용되지 않습니다.

blink속성은 Internet Explorer에서는 지원하지 않기 때문입니다.

"객체.메소드"의 원리를 이해했다면 어렵지 않을것입니다.


이번에는 String 객체로 문자열을 다루는 방법에 대하여 알아보겠습니다.
다음은 해당 메소드와 그에 관한 설명입니다.

메소드 설명
charAt(index) 지정된 위치의 문자를 반환합니다.
charCodeAt([index]) 지정된 위치에 있는 문자의 코드(ISO Latin-1)값의 수를 반환합니다.
concat("문자열1,문자열2,...문자열n") 문자열을 연결하여 새로운 문자열을 반환합니다.
indexOf("string") 문자열의 왼쪽부터 검사하여 처음으로 나타나는 string을 반환합니다.
lastIndexOf("string") 문자열의 오른쪽부터 검사하여 처음으로 나타나는 string을 반환합니다.
match(regexp) 인수로 전달된 문자열과 일치하는 것을 찾습니다.
replace(regexp, newSubstr) 전달된 문자열을 새로운 문자열로 대치합니다.
search(regexp) 지정된 문자열이 포함되어 있는지 검색합니다.
slice(start_index, end_index) 문자열의 일부를 추출하여 배열을 만듭니다.
substring(index1, index2) 지정된 위치에 있는 문자열 앞부분을 반환합니다.
substr(start_index, length) 문자열의 지정된 개수 만큼 문자를 반환합니다.
slipt(separator, limit) 문자열을 지정된 인수로 분리합니다.
toLowerCase() 문자열을 소문자로 변환합니다.
toUpperCase() 문자열을 대문자로 변환합니다.

 

다음의 예제로 각각의 특성을 알아봅니다.

<HTML>
<HEAD>
<TITLE>charAt(index) 메소드</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
var tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7, tmp8, tmp9, tmp10, tmp11, tmp12, tmp13, tmp14;
var re=/Java/gi;
var str1="JavaScript"
var str2="String"
tmp1="JavaScript String".charAt(0);
tmp2="JavaScript String".charAt(4);
tmp3="JavaScript String".charCodeAt(3);
tmp4=str1.concat(str2);
tmp5="JavaScript String".indexOf("v");
tmp6="JavaScript String".lastIndexOf("r");
tmp7=str1.replace(re, "자바");
tmp8=str1.search(re);
tmp9=str1.slice(3,8);
tmp10=str1.substring(2,6);
tmp11=str1.substr(2,6);
tmp12=str1.split("v",6);
tmp13=str1.toUpperCase();
tmp14=tmp13.toLowerCase();

document.write("charAt(0) - "+"JavaScript String의 첫 번째 문자 : "+tmp1+"<br><br>");

document.write("charAt(4) - "+"JavaScript String의 다섯 번쩨 문자 : "+tmp2+"<br><br>");

document.write("charCodeAt(3) - "+"JavaScript String의 네 번째 문자의 ISO Latin-1의 값 : "+tmp3+"<br><br>");

document.write("concat - "+str1+"와 "+str2+"을 연결하면 : "+tmp4+"<br><br>");

document.write("indexOf("+"v"+") - "+"JavaScript String의 문자중 왼쪽에서 첫 번째 있는 'v'는? :

"+tmp5+"<br><br>");

document.write("lastIndexOf("+"r"+") - "+"JavaScript String의 문자중 오른쪽에서 첫 번째 있는 'r'은 :

"+tmp6+"<br><br>");

document.write("replace(re, "+"자바"+") - "+"JavaScript가 변경되면 : "+tmp7+"<br><br>");

document.write("search(re) - "+"Jave가 있는가? : "+tmp8+"<br><br>");

document.write("slice(3,8) - "+"JavaScript중 v에서 r까지 : "+tmp9+"<br><br>");

document.write("substring(2,6) - "+"JavaScript v에서 c까지 : "+tmp10+"<br><br>");

document.write("substr(2,6) - "+"JavaScript v에서 뒤로 6자를 출력 : "+tmp11+"<br><br>");

document.write("split("+"v"+",6) - "+"JavaScript v를 중심으로 분리 : "+tmp12+"<br><br>");

document.write("toUpperCase() - "+"JavaScript를 대문자로 : "+tmp13+"<br><br>");

document.write("toLowerCase() - "+tmp13+"를 소문자로 : "+tmp14+"<br><br>");

//-->
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>

<실행결과>

charAt(0) - JavaScript String의 첫 번째 문자 : J

charAt(4) - JavaScript String의 다섯 번쩨 문자 : S

charCodeAt(3) - JavaScript String의 네 번째 문자의 ISO Latin-1의 값 : 97

concat - JavaScript와 String을 연결하면 : JavaScriptString

indexOf(v) - JavaScript String의 문자중 왼쪽에서 첫 번째 있는 'v'는? : 2

lastIndexOf(r) - JavaScript String의 문자중 오른쪽에서 첫 번째 있는 'r'은 : 13

replace(re, 자바) - JavaScript가 변경되면 : 자바Script

search(re) - Jave가 있는가? : 0

slice(3,8) - JavaScript중 v에서 r까지 : aScri

substring(2,6) - JavaScript v에서 c까지 : vaSc

substr(2,6) - JavaScript v에서 뒤로 6자를 출력 : vaScri

split(v,6) - JavaScript v를 중심으로 분리 : Ja,aScript

toUpperCase() - JavaScript를 대문자로 : JAVASCRIPT

toLowerCase() - JAVASCRIPT를 소문자로 : javascript



JavaScript String Object

≪ PreviousNext Reference ≫

String Object

The String object is used to manipulate a stored piece of text.

String objects are created with new String().

Syntax

var txt = new String("string");

or more simply:

var txt = "string";

For a tutorial about the String object, read our JavaScript String Object tutorial.


String Object Properties

PropertyDescription
constructorReturns the function that created the String object's prototype
lengthReturns the length of a string
prototypeAllows you to add properties and methods to an object

String Object Methods

MethodDescription
charAt()Returns the character at the specified index
charCodeAt()Returns the Unicode of the character at the specified index
concat()Joins two or more strings, and returns a copy of the joined strings
fromCharCode()Converts Unicode values to characters
indexOf()Returns the position of the first found occurrence of a specified value in a string
lastIndexOf()Returns the position of the last found occurrence of a specified value in a string
match()Searches for a match between a regular expression and a string, and returns the matches
replace()Searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring
search()Searches for a match between a regular expression and a string, and returns the position of the match
slice()Extracts a part of a string and returns a new string
split()Splits a string into an array of substrings
substr()Extracts the characters from a string, beginning at a specified start position, and through the specified number of character
substring()Extracts the characters from a string, between two specified indices
toLowerCase()Converts a string to lowercase letters
toUpperCase()Converts a string to uppercase letters
valueOf()Returns the primitive value of a String object

String HTML Wrapper Methods

The HTML wrapper methods return the string wrapped inside the appropriate HTML tag.

MethodDescription
anchor()Creates an anchor
big()Displays a string using a big font
blink()Displays a blinking string
bold()Displays a string in bold
fixed()Displays a string using a fixed-pitch font
fontcolor()Displays a string using a specified color
fontsize()Displays a string using a specified size
italics()Displays a string in italic
link()Displays a string as a hyperlink
small()Displays a string using a small font
strike()Displays a string with a strikethrough
sub()Displays a string as subscript text
sup()Displays a string as superscript text

번호 제목 글쓴이 날짜 조회 수
217 iframe auto resize (cross browsing) 황제낙엽 2011.05.13 658
216 Javascript CORS/XSS 극복하는(피하는) 방법 file 황제낙엽 2017.07.31 648
215 [JavaScript Tutorials] Introducing the closure (해석중) 황제낙엽 2009.04.10 555
214 입력받은 날짜와 현재 날짜와의 비교 함수 황제낙엽 2019.08.02 500
213 Javascript 를 사용하여 Binary File 읽기 황제낙엽 2010.09.29 500
212 url encode & decode 황제낙엽 2011.10.30 469
211 자바스크립트로 서버의 XML파일을 접근 (실패했슴) 황제낙엽 2005.12.11 444
210 XMLHttpRequest 의 이벤트 onreadystatechange 황제낙엽 2012.05.30 412
209 Defining classes and inheritance (클래스 정의와 상속) 황제낙엽 2011.03.24 392
» Javascript 내장객체 String 황제낙엽 2007.04.10 392
207 JavaScript Array.push Performance 황제낙엽 2011.11.21 380
206 JavaScript Touch and Gesture Events iPhone and Android 황제낙엽 2012.04.12 337
205 Faster JavaScript Memoization For Improved Application Performance 황제낙엽 2011.11.04 333
204 진행 상황 추적하기(XMLHttpRequest.readyState) file 황제낙엽 2012.05.23 324
203 String Performance: Getting Good Performance from Internet Explorer (IE7) 황제낙엽 2011.11.24 312
202 window.postMessage() 황제낙엽 2020.07.29 303
201 unshift() Method 황제낙엽 2009.03.02 287
200 CORS(Cross-Origin Resource Sharing) - 5 file 황제낙엽 2017.03.07 261
199 Jasmine 테스트 및 CI 구축 가이드 황제낙엽 2016.11.16 254
198 정규식 정리 황제낙엽 2008.11.24 252