2022.04.22

String(문자)


String 전역(: 자바스크립트 전체에서 쓸 수 있는)객체는 문자열의 생성자
new String ()
문자데이터를 만들때 리터럴방식 ('', "", ``)사용

properties

  • String legnth

    //변수str 문자데이터의 글자가 총 몇개에요?
    //length는 프로토타입으로 사용 가능하기때문에 변수에 담지 않아도 사용됨
    const str = 'abcdefg'
    console.log(str.length) //7
    console.log('a bcdefg'.length) //8 --> 공백도 문자취급

Methods

  • String.prototype.indexOf()
    프로토타입에 의해 지정된 메소드는 메모리에 딱 한번만 만들어지고
    new라는 생성자 함수에서 인스턴스로 언제든지 활용할 수 있음

    // 호출한 String 객체에서 주어진 값과 일치하는 첫 번째 인덱스(숫자'0'부터)를 반환합니다. 
    // 일치하는 값이 없으면 -1을 반환 
    const paragraph = 'Laughter is the best medicine. No news is good news' 
    const search = 'is' 
    const indexOfFisrt = paragraph.indexOf(search); 
    console.log(indexOfFisrt) //9`
    // new String() 생성자 함수대신에 ''(리터럴)방식에 직접적으로 indexOf()라는 메소드를 쓸 수 있음
    const hello = 'Hello World'.indexOf('l')
    console.log(hello) // 2
    //Boolean 데이터로 출력하고 싶다면
    const hello = 'Hello World'
    // 비교연산자를 통해 '일치하는 값이 없으면 -1을 반환'하는 속성을 이용하면 된다
    console.log(hello.indexOf('Hello') !== -1) //true
  • String.prototype.split()
    문자열을 분할해주는 메서드

    const str = 'Hello World'
    const arr = str.split(' ')
    console.log(arr) //['Hello', 'World']
    
    const users = 'sunny, jeesie, amy'
    console.log( users.split(', ')) //['sunny', 'jeesie', 'amy']
  • toLowerCase, toUpperCase
    소문자, 대문자

    const str = "HELLO"
    console.log (str.toLowerCase()) //hello
  • String.prototype.slice()
    문자열의 일부를 추출하면서 새로운 문자열을 반환
    시작하는 index부터 종료점 index전까지 추출됨

    const hello = 'Hello World' 
    console.log(hello.slice(6 , 11)) //World
  • Stirng.prototype.replace()
    replace는 두개의 인수를 받음
    해당 문자데이터에서 첫번째 인수에 있는 문자를 찾아서 두번째 인수에 있는 문자로 바꿔주세용

    const hello = 'Hello World' 
    console.log(hello.replace('Hello', 'Honey')) //Honey World

    String.prototype.match()
    특정한 문자데이터에서 정규표현식을 통해서
    특정한 문자를 일치시켜 배열데이터 내부에서 추출시켜서 사용가능

    // 이메일주소의 아이디만 추출하고 싶을때 
    // (/.+(?=@)/) 정규표현식RegExp 
    const email = 'email@gmail.com' 
    console.log(email.match(/.+(?=@)/)) 
    //['email', index: 0, input: 'email@gmail.com', groups: undefined] 
    // 그 다음 배열의 첫번째 부분만 추출하면 되기때문에 
    console.log(email.match(/.+(?=@)/)[0]) //email
  • String.prototype.trim()
    문자의 앞뒤로 연결된 공백문자를 제거해줌

    const hello = ' Hello World ' 
    console.log(hello.trim()) //Hello World
  • String.prototpye.includes()
    들어있냐 여부에 따라 true, false반환

    const hello = ' Hello World ' 
    console.log(hello.includes('o')) //true

+ Recent posts