카테고리 없음

[JS] JS String 내장함수 정리

waveTocode 2023. 5. 9. 01:20

| String 내장함수

  • length : 문자열의 길이
       
         var txt="ABCDEFGHIJKLMN";
         console.log(txt.length);     // 결과값: 14
 
  • indexOf: 괄호 안의 단어의 인덱스 값을 찾아
 
        var str="Please locate where 'locate'";
        console.log(str.indexOf("locate"));  // 결과값: 7
        // console.log(str.indexof("choi")); 없는 단어는 -1 리턴
 
  • search: 문자열에서 단어의 인덱스값을 찾아 리턴
 
        var str="Please locate where 'locate'";
        console.log(str.search("locate"));   //결과값: 7
 
  • slice(인덱스,인덱스-1):  인덱스~인덱스-1까지 문자열 자르기
 
        var str="Apple, Banana, Kiwi";
        console.log(str.slice(7,13));       //출력값: Banana
        console.log(str.slice(7));            //출력값: Banana, Kiwi -- 2번째 인덱스가 비어 있으면 끝까지
        console.log(str.slice(-12,-6));     //출력값: Banana --뒤에서부터 거꾸로 감
        console.log(str.slice(-2));
  • substring: 문자열 자르기
 
        var str="Apple, Banana, Kiwi"; //출력값: Banana
        console.log(str.substring(7,13));
  • substr(인덱스1,n): 인덱스1부터 n개 문자열 자르기
     
        var str="Apple, Banana, Kiwi";
        console.log(str.substring(7,6)); //7번 인덱스부터 6글자
 
  • replace: 문자열 치환
 
        var str1="Please visit here";
        var str2=str1.replace("here","there");
        console.log(str2);  // 결과값: Please visit there

        var str1="Please visit here here here";
        var str2=str1.replace("here","there");   //맨 앞에 하나만 바뀜
        console.log(str2);  //결과값: Please visit there here here

        var str1="Please visit here here here";
        var str2=str1.replace(/here/g,"there"); // /찾을 단어/: 정규 표현식(하나만 바뀜) /찾을 단어/
        // g: 모두 바뀜 :global(=전체)를 의미
        console.log(str2);

        var str1="Please visit HERE Here HeRe";
        var str2=str1.replace(/here/ig,"there");  //i: ignore 대소문자 구별 X
        console.log(str2);
 
  • toUpperCase: 모두 대문자로
 
        var str1="Please visit HERE Here HeRe";
        console.log(str1.toUpperCase()); //결과값: PLEASE VISIT HERE HERE HERE
 
  • toLowerCase: 모두 소문자
 
        var str2="Please visit HERE Here HeRe";
        console.log(str2.toLowerCase()); //결과값: please visit here here here
 
  • trim() : 앞 뒤 공백제거
 
        var str10="             Hello               World            .";
        console.log(str10);            // Hello World
        console.log(str10.trim());  // HelloWorld
 
  • pasStart: 앞을 n1개가 될 때 까지 n2로 채우기
 
        var str11="15";
        console.log(str11.padStart(8,0));  //00000015
 
        //특정 자릿수를 통일하기 위해 사용 : 예) 날짜를 두자릿수로 통일
        var str12="3";
        console.log(str12.padStart(2,0));
 
  • padEng(n1,n2):  뒤를 n1개가 될 때 까지 n2로 채우기
 
        var str12="13";
        console.log(str12.padEnd(4,0));   //1300
 
  • charAt: 문자열 반환
 
        var str13="Hello World";
        console.log(str13.charAt(0));  //결과값: H
 
  • split: 문자열 구분자로 자르기
 
        var tags="키보드,기계식,블루투스";
        var arr1=tags.split(",");
        console.log(arr1);  //결과값: ['키보드', '기계식', '블루투스']