문자열

  1. 문자열 선언
let str1 = '문자열';                //원시(primitive)문자열 타입   type:string
let str2 = new String('문자열');    //문자열 객체                  type:object
                                    //긴 문자열을 여러줄에 나누어서 표시  백슬래시는 코드 실행 시점에서는 제거됨. 
let str3 = ' this \                 
              is  \
             new line' 
                                    //줄바꿈까지 유지됨
let str4 = ` this
             is
            new line`            
  • 문자열 == 문자열, 문자열 === 문자열, 문자열 == 객체 : true
  • 객체 == 객체 객체 === 객체 : false
  • 문자열객체 사용 시 객체 자체를 비교하면 안됨. 문자열로 캐스팅한 다음에 사용
  • eval() : 문자열을 입력받아 소스코드(자바스크립트 실행코드)로 변환
  • eval(문자열) –> 변환됨
  • eval(객체) –> 객체를 그대로 반환
  • eval(객체.valueOf()) –> 객체는 원시문자열로 변화해서 사용
  1. 리터털 선언과 동시에 값을 적용해서 생성
    • 문자열 리터털:
    • 객체 리터럴: 객체 선언과 동시에 변수에 값을 대입
    • 템플릿 리터럴 : 표현식을 허용하는 문자열 리터럴. 런타임 시점에 표현식(${변수명}) 에 값이 대입됨.
    • 태그드 리터럴
       let str = '문자열'                           //문자열
       let obj = {name:'홍길동', age:20}            //객체
       let template = `${str} 변수 의 값이 지정됨`  //템플릿
       let result = taggedFunc`${str}입장`          //태그드 템플릿
       function taggedFunc(strings, exp) {
         console.dir(strings, exp)  
         return exp + strings.toString();
       }
      
  2. 함수
    • 앞뒤 공백제거 : trim(), trimStart(), trimLeft(), trimEnd(), trimRight() : IE는 지원안함
    • 문자열 자르기 : slice(?start,?end), substring(start,?end), substr(from,?length)
    • 문자열 찾기 : indexOf(searchString, ?position), lastIndexOf(searchString, ?position), charAt(pos), includes(searchString, ?position), search(regexp)/search(searcher), match(regexp)/match(matcher) : regexp는 일치하는 모든 값을 배열로 반환, 문자열은 길이가 1인 배열

trim함수 구현

    <!--[if lte IE 8]>    
        <script> 
            String.prototype.trim = function() { 
                return this.replace(/^\s+|\s+$/g,""); 
            } 
        </script> 
    <![endif]-->  
    <script>
        //IE에서는 프로토타입 함수로 별도로 구현
        String.prototype.ltrim = function(){      //왼쪽공백제거
            return this.replace(/^\s+/,'');
        }
        String.prototype.rtrim = function(){      //오른쪽공백제거
            return this.replace(/\s+$/,'');
        }
        String.prototype.trimAll = function(){    //문자열 안에 있는 모든 공백 제거(정규표현식)
            return this.replace(/\s/g,'');
        }
        String.prototype.trimAll2 = function(){    //문자열 안에 있는 모든 공백 제거
            rreturn this.split(' ').filter(el => el!= '').join('')
        }
    </script>

특정문자열을 태그로 감싸기

    <script>
    let str = "@해님 @good @choi 댓글입니다."
    str = str.replace(/(@[a-zA-Z가-힣]*)/gi, '<span>$1</span>');
    consoloe.log(str) 
    //출력결과  : "<span>@해님</span> <span>@good</span> <span>@choi</span> 댓글입니다."
    </script>
  1. 날짜 포맷과 문자열 변환
    • 협정세계시 : UTC(Coordinated Universal Time) == GMT(Greenwich Mean Time)
let today = new Date()
today.toString()       // 영어권                   지역시간(locale)   'Fri Nov 05 2021 18:58:50 GMT+0900 (한국 표준시)'
today.toGMTString()    // ==today.toUTCString()    표준시간(UTC)      'Fri, 05 Nov 2021 09:58:50 GMT' 
today.toISOString()    // ==today.toJSON()         표준시간(UTC)      '2021-11-05T09:58:50.705Z'

//locale시간을 ymd로 표시
today.getFullYear()+'-'+
     ('0'+(today.getMonth()+1)).slice(-2)+'-'+
     ('0'+today.getDate()).slice(-2)+'T'+
     ('0'+today.getHours()).slice(-2)+':'+
     ('0'+today.getMonth()).slice(-2) +':'+
     ('0'+today.getDate()).slice(-2)  

Categories:

Updated: