For developer/JAVASCRIPT

(JavaScript)문자열 객체

프린이0218 2020. 4. 11. 15:10
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>문자열 객체</title>
<script type="text/javascript">

//문자열 객체:문자형 데이터를 객체로 취급하는 것으로 자바스크립트에서 가장 많이 사용

/*문자열 객체 생성
 ①var t = new String("hello world");
 ②var t = "hello world";
 */
 
 var t ="My name is HyungGyu";
 
 //charAt(index):문자열에서 인덱스 번호에 해당하는 문자 반환
 document.write(t.charAt(3));  //->n반환
 
 //indexOf("찾을 문자"):문자열 왼쪽에서 부터 비교하여 찾을문자가 있으면 그 문자의 인덱스 번호 출력,만약 없으면 -1출력
 document.write(t.indexOf("is")); //-> 8 반환
 
 //lastIndexOf("찾을문자"):문자열 오른쪽에서 부터 비교하여 찾을 문자가 있으면 그 문자 인덱스 번호 출력,만약 없으면 -1출력
 document.write(t.lastIndexOf("is"));
 
 //match("찾을 문자"):문자열 왼족에서 부터 비교하여 찾을 문자가 있으면 그 문자 그대로 반환,만약 없으면 null 반환
 document.write(t.match("hyung")); //->null  반환
 document.write(t.match("Hyung")); //->Hyung 반환
 
 //replace("바꿀문자","새 문자"):바꿀문자가 문자열에 있으면 새 문자로 치환함.
 document.write(t.replace("My","your")); //-> your name is HyungGyu
 
 //slice(a,b):a개의 문자를 먼저 자르고 b부터 문자를 잘라서 남은 문자 반환,b자리에 -값이 있으면 뒤에서부터 카운트함.
 document.write(t.slice(3,7)); //->name 반환
 
 //substring(a,b):a 인덱스부터 b인덱스 이전!! 구간의 문자를 반환
 document.write(t.substring(3,7)); //-> name 반환
 
 //substr(a,문자개수):a인덱스부터 문자개수만큼 출력
 document.write(t.substr(8,2)); //->is 출력
 
 //split("문자"):지정한 문자를 기준으로 문자 데이터를 나누어 배열에 저장
 var arr=t.split(""); //-> 공백을 기준으로 나누어 배열에 저장
 
 //toLowerCase(); //모든 문자 소문자로 변환
 //toUpperCase(); //모든 문자 대문자로 변환
 
 //length : 문자열에서 문자의 개수를 반환(공백포함)
 document.write(t.length);
 
 //concat("새로운 문자") : 문자열에 새로운 문자열을 결합
 document.write(t.concat("thank")); //->My name is HyungGyuthank
 
 //charCodeAt(index):인덱스에 해당하는 문자의 아스키 코드값 반환
 //fromCodeAt():아스키 코드값에 해당하는 문자를 반환
 
 //trim():문자의 앞 또는 뒤에 공백 문자열 삭제
 
	
 </script>
</head>
<body>

</body>
</html>