본문 바로가기

Webstoryboy

Category

Explanation

JAVASCRIPT

[Javascript] 문서 객체

문자 객체

문자객체(String Object)는 문자와 관련된 객체입니다.


문자 객체 생성

var 변수 = new String(문자형 데이터)

String 객체의 속성
종류 설명
length 문자열의 길이를 가져옵니다.
String 객체의 메서드
종류 설명
charAt() 문자열에서 인덱스 번호에 해당하는 문자를 반환합니다.
charCodeAt() 문자열에서 인덱스에 대한 유니코드를 나타내는 0부터 65535 사이의 정수를 반환합니다.
codePointAt() 문자열에서 인덱스에 대한 유니코드 포인트 값인 아닌 정수를 반환합니다.
concat() 여러 개의 문자열을 새 문자열로 반환합니다.
endsWith() 문자열에서 특정 문자열로 끝나는지를 확인합니다.
includes() 하나의 문자열이 다른 문자열에 포함되어 있는지를 판별합니다.
includes() 하나의 문자열이 다른 문자열에 포함되어 있는지를 판별합니다.
indexOf() 문자열에서 왼쪽부터 주어진 값과 일치하는 첫 번째 인덱스를 반환합니다
lastIndexOf() 문자열에서 오른쪽부터 주어진 값과 일치하는 첫 번째 인덱스를 반환합니다.
localeCompare() 기준 문자열과 비교했을 때 비교 대상 문자열의 정렬상태를 알려줍니다.
match() 문자열에서 왼쪽부터 찾은 문자와 일치하는 문자를 반환합니다.
normalize() 문자열에서 유니코드를 따라 정규화된 형태로 반환합니다.
padEnd() 현재 문자열에 다른 문자열을 채워, 주어진 길이를 만족하는 새로운 문자열을 반환합니다.
padStart() 현재 문자열의 시작을 다른 문자열로 채워, 주어진 길이를 만족하는 새로운 문자열을 반환합니다.
repeat() 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환합니다.
replace() 문자열에서 왼쪽부터 바꿀 문자를 찾아 새로운 문자로 변환합니다.
search() 문자열에서 왼쪽부터 찾는 문자를 찾은 후 최초로 일치하는 인덱스를 반환합니다.
slice() 문자열에서 특정 위치의 문자열을 추출해 반환합니다.
split() 구분자를 이용하여 여러 개의 문자열로 반환합니다.
startsWith() 문자열에서 특정 문자로 시작하는지 확인하여 결과를 true 혹은 false로 반환합니다.
substr(start, count) start부터 count만큼 문자열을 잘라서 반환합니다.
substring(start, end) start부터 end까지 문자열을 잘라서 반환합니다.
toLowerCase() 문자열을 소문자로 바꾸어 반환합니다.
toUpperCase() 문자열을 대문자로 바꾸어 반환합니다.
trim() 문자열 양 끝의 공백을 제거합니다.
HTML 관련 객체 메서드

현재는 사용하지 않는 태그이기 때문에 다음의 객체 메서드들도 사용하지 않습니다.

종류 설명
anchor() a 태그로 문자열을 감싸 리턴합니다.
big() 텍스트 양 끝에 HTML <big> 태그를 삽입합니다.
blink() 텍스트 양 끝에 HTML <blink> 태그를 삽입합니다.
bold() 텍스트 양 끝에 HTML <b> 태그를 삽입합니다.
fixed() 텍스트 양 끝에 HTML <tt> 태그를 삽입합니다.
fontcolor() 텍스트 양 끝에 HTML <font> 태그를 삽입합니다.
fontsize() 텍스트 양 끝에 HTML <font> 태그를 삽입합니다.
italics() 텍스트 양 끝에 HTML <i> 태그를 삽입합니다.
link(href) a 태그에 href 속성을 지정해 리턴합니다.
small() 텍스트 양 끝에 HTML <small> 태그를 삽입합니다.
strike() 텍스트 양 끝에 HTML <strike> 태그를 삽입합니다.
sub() 텍스트 양 끝에 HTML <sub> 태그를 삽입합니다.
sup() 텍스트 양 끝에 HTML <sup> 태그를 삽입합니다.

Sample1

문자열에서 많이 사용하는 예제입니다.

결과
Hello I'm a webstoryboy. I'm not a student.
인덱스(6)에 저장된 문자[charAt(6)] : I
주어진 값과 왼쪽부터 일치하는 인덱스[indexOf(a)] : 10
문자열 인덱스 30부터 주어진 값과 왼쪽부터 일치하는 인덱스[indexOf('a',30)] : 33
주어진 값과 오른쪽부터 일치하는 인덱스[indexOf(a)] : 33
문자열 인덱스 30부터 주어진 값과 오른쪽부터 일치하는 인덱스[indexOf('a',30)] : 10
인덱스 11부터 12글자 반환[substr()] : webstoryboy
인덱스 11부터 23까지 반환[substring()] : webstoryboy
문자열 교체[replace()] : Hello I'm a webs. I'm not a student.
문자열 일치 후 문자열 반환[match()] : webstoryboy
문자열 일치 후 인덱스 반환[search()] : 12
소문자 변경[toLowerCase()] : hello i'm a webstoryboy. i'm not a student.
대문자 변경[toUpperCase()] : HELLO I'M A WEBSTORYBOY. I'M NOT A STUDENT.
html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>string</title>
    <script>
        let text = "Hello I'm a webstoryboy. I'm not a student.";
        
        document.write(text,"<br>");
        document.write("인덱스(6)에 저장된 문자[charAt(6)] : " + text.charAt(6),"<br>");
        document.write("주어진 값과 왼쪽부터 일치하는 인덱스[indexOf(a)] : " + text.indexOf("a"),"<br>");
        document.write("문자열 인덱스 30부터 주어진 값과 왼쪽부터 일치하는 인덱스[indexOf('a',30)] : " + text.indexOf("a",30),"<br>");
        document.write("주어진 값과 오른쪽부터 일치하는 인덱스[indexOf(a)] : " + text.lastIndexOf("a"),"<br>");
        document.write("문자열 인덱스 30부터 주어진 값과 오른쪽부터 일치하는 인덱스[indexOf('a',30)] : " + text.lastIndexOf("a",30),"<br>");
        document.write("인덱스 11부터 12글자 반환[substr()] : " + text.substr(11,12),"<br>");
        document.write("인덱스 11부터 23까지 반환[substring()] : " + text.substring(11,23),"<br>");
        document.write("문자열 교체[replace()] : " + text.replace("webstoryboy","webs"),"<br>");
        document.write("문자열 일치 후 문자열 반환[match()] : " + text.match("webstoryboy"),"<br>");
        document.write("문자열 일치 후 인덱스 반환[search()] : " + text.search("webstoryboy"),"<br>");
        document.write("소문자 변경[toLowerCase()] : " + text.toLowerCase(),"<br>");
        document.write("대문자 변경[toUpperCase()] : " + text.toUpperCase(),"<br>");
    </script>
</head>
<body>
    
</body>
</html>

Sample2

글자를 span 태그로 만들기 예제입니다.

결과

편안함이 끝나고 궁핍이 시작될 때 인생의 가름침이 시작된다

편안함이 끝나고 궁핍이 편안함이시작될 인생의 가름침이 시작된다
html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>글자를 span 태그로 만들기</title>
    <style>
        span {text-decoration: underline;}
    </style>
</head>
<body>
    <h2 id="h2">편안함이 끝나고 궁핍이 시작될 때 인생의 가름침이 시작된다</h2>
    
    <script>
        window.onload = function(){
            let text = document.getElementById('h2').textContent;
        
            let spanText = text.split(" ").join("</span> <span>")
                spanText = "<span>" + spanText + "</span> ";
        
            let spanText2 = text.split("").join("</span> <span>")
                spanText2 = "<span>" + spanText2 + "</span> ";
            
            document.write(spanText,"<br>");
            document.write(spanText2);
        };
    </script> 
</body>
</html>

Sample3

toUpperCase(), substring() 예제입니다.

결과
HWANG SNAG YEON
010-2039-****
html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>toUpperCase(), substring()</title>
    <script>
        let userName = prompt("영문 이름을 입력하세요!","");
        let userNumber = prompt("핸드폰 번호를 입력하세요!","");
        
        let upper = userName.toUpperCase();
        let star = userNumber.substring(0, userNumber.length-4)+"****";
        
        document.write(upper,"<br>");
        document.write(star);
    </script>
</head>
<body>
    
</body>
</html>

Sample4

이메일 유효성 검사하기 예제입니다.

결과
이메일 형식이 잘못되었습니다.
html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>이메일 유효성 검사하기</title>
    <script>
        let useEmail = prompt("당신의 이메일 주소는?","");
        let arrUrl = [".co.kr",".com",".net",".or.kr",".go.kr"];
        
        let check1 = false;
        let check2 = false;
        
        if(useEmail.indexOf("@")>0) check1=true;
        
        for(let i=0; i<arrUrl.length; i++){
            if(useEmail.indexOf(arrUrl[i])>0) check2=true;
        }
        
        if(check1 && check2){
            document.write(useEmail);
        } else {
            document.write("이메일 형식이 잘못되었습니다.");
        }
    </script>
</head>
<body>
    
</body>
</html>

참고(Reference)

  • MDN JavaScript

더보기

인스타그램 보기 바로가기

포트폴리오 스터디 바로가기

유튜브 영상보기 바로가기