var str = "누구든지 체포 또는 구속을 당한 때에는 "+
        "즉시 변호인의 조력을 받을 권리를 가진다. 다만, " +
        "형사피고인이 스스로 변호인을 구할 수 없을 때에는" + 
        "법률이 정하는 바에 의하여 국가가 변호인을 붙인다.";

 

+를 이용해서 문자열을 연결하여 str 변수에 저장하였다.

 

 

 

charAt()

document.write(str.charAt(2),str.charAt(3),"<br>");

charAt으로 문자열에서 인덱스 위치에 해당하는 한글자를 뽑을 수 있다. 0부터 시작하기 때문에 charAt(2)는 '든', charAt(3)은 '지'로 '든지'가 출력된다.

 

 

 

indextOf()

lastIndexOf()

  	document.write(str.indexOf("변호인"),"<br>");//처음부터 검색
        document.write(str.indexOf("변호인",38),"<br>");
        document.write(str.indexOf("변호사"),"<br>");
        document.write(str.lastIndexOf("변호인"),"<br>");//마지막부터 검색

indextOf("문자")는 문자가 있는 위치를 나타내준다. 처음부터 검색해서 나오는 문자 위치값을 출력한다.

("문자",38)처럼 숫자를 넣어주면 그 이후부터 검색한다.

lastIndexOf는 마지막부터 검색한다.

찾는 문자열이 없으면 -1을 리턴한다.

 

 

length : 문자열 개수

document.write("문자열 개수 : ", str.length,"<br>");

 

 

replace() : 문자열 바꾸기

        document.write(str.replace("변","신"),"<br>");
        document.write(str,"<br>");

replace로 특정 문자열을 특정 문자열으로 바꾼다.

최초 검색된 것만 변경하고 변경사항은 저장되지 않기 때문에 다시 str을 출력할 경우 replace전 원래 문장이 나오게 된다.

 

str = str.replace("변","신");

변경한 것을 저장하고 싶으면, 변경하고 바로 변수에 저장해야한다.

 

 

 

replaceAll() : 문자열 모두 바꾸기

	str = str.replaceAll("변","신");
        document.write(str,"<br>");

replaceAll을 이용하면 모든 문자열을 바꿀 수 있다.

 

 

 

substr / substring : 문자열 부분추출

        var str = "Hello World Test Korea Soccer Baseball";
        document.write(str.substr(4,10),"<br>") //o World Te
        document.write(str.substring(4,10),"<br>") //o Worl
	document.write(str.substr(4),"<br>") //o World Test Korea Soccer Baseball
        document.write(str.substring(4),"<br>") //o World Test Korea Soccer Baseball

새로운 문장으로 문자열 부분추출 메서드를 확인한다.

substr(4,10) : 4번 인덱스부터 10글자

substring(4,10) : 4번 인덱스부터 10번 인덱스 전까지 추출

substr는 시작인덱스와 글자수를 설정하고, substring은 시작인덱스와 끝인덱스(포함x)를 지정한다.

substr(4), substring(4) 모두 4번 인덱스부터 끝까지로 같은 결과를 확인할 수 있다.

 

 

 

toUpperCase(), toLowerCase()

        document.write(str.toUpperCase()); //HELLO WORLD TEST KOREA SOCCER BASEBALL
        document.write(str.toLowerCase()); //hello world test korea soccer baseball

toUpperCase() : 대문자로 변환

toLowerCase() : 소문자로 변환

 

 

charCodeAt() : 문자코드값

        var str2 = '가나다';
        document.write(str2.charCodeAt(0), "<br>"); //44032
        document.write(str2.charCodeAt(1), "<br>"); //45208

str2.charCodeAt(0)으로 '가나다'문자열의 0번째 인덱스에있는 '가'의 문자코드값을 가져왔다.

인덱스값을 1로 하면 '나'의 문자코드값을 확인할 수 있다.

 

 

 

String.fromCharCode() : 문자코드값의 문자

document.write(String.fromCharCode(65), "<br>"); //A

문자코드 65의 문자를 확인할 수 있다. 65번인 A가 출력된다.