Skip to content
JONGMINFIRE.DEV

Javascript 문자열 메소드

Javascript


문자열 객체에 관한 메소드에 대해서 알아본다.


  • charAt()


    1charAt(index);

    charAt() 메소드는 문자열의 index에 해당하는 문자형 데이터를 반환하는 함수이다.


    1let str = "Hello";
    2let result = str.charAt(1);
    3
    4// result = "e"

  • IndexOf() / lastIndexOf()


    1IndexOf("찾는 문자", index);
    2lastIndexOf("찾는 문자");

    IndexOf()는 문자열 왼쪽부터, lastIndexOf()는 문자열 오른쪽 부터 찾는 첫번째 문자의 index를 반환하는 함수이다. 찾는 문자 이외에 index를 지정해주면 index부터 탐색하고 해당되는 문자가 없으면 -1을 반환한다.


    1let str = "Hello";
    2let a = str.indexOf("l"); // 첫번째 문자 이므로 a = 2
    3let b = str.lastIndexOf("l"); // 오른쪽 부터 찾으므로 b = 3
    4let c = str.indexOf("J"); // c = -1

  • replace()


    1replace("찾는 문자", "바꿀 문자");

    replace() 함수는 문자열 왼쪽부터 찾을 문자를 찾아 최초로 일치하는 문자를 바꿀 문자로 바꾼다.


    1let str = "Hello World Hello";
    2let result = str.replace("Hello", "Good");
    3
    4// 최초로 일치하는 문자만 바뀌므로
    5// result = "Good World Hello"

    최초로 일치하는 문자말고 모든 문자를 치환하기 위해서는 정규식을 사용해야 한다.

    / 검색값 / : '//' 사이에 검색할 문자 입력

    검색값1 | 검색값2 | ... : 여러개의 문자를 바꾸고 싶은 경우 '|' 로 구분

    g : 발생한 모든 패턴에 대해 전역 검색

    i : 대/소문자 구분을 무시

    m : 여러줄 검색


    1let str = "Mr Blue has a blue house and a Blue car";
    2
    3let result1 = str.replace(/blue/g, "Red");
    4// result1 = "Mr Blue has a Red house and a Blue car";
    5
    6let result2 = str.replace(/blue/gi, "Red");
    7// result2 = "Mr Red has a Red house and a Red car";

  • substring() / substr()


    1substring(startIndex, endIndex);
    2substr(startIndex, 문자개수);

    substring() 함수는 startIndex 부터 endIndex 앞까지의 문자열을 잘라서 반환해주는 함수이고, substr() 함수는 startIndex 부터 문자개수 만큼 문자열을 잘라서 반환해주는 함수이다.


    1let str = "Hello World";
    2
    3let result1 = str.substring(0, 5);
    4// result1 = "Hello";
    5
    6let result2 = str.substr(6, 5);
    7// result2 = "World";

  • split()


    1split("문자");

    split() 함수는 입력 문자를 기준으로 문자열을 잘라서 배열에 담아 배열 객체를 반환해주는 함수이다.


    1let str = "Hello#World";
    2
    3let result = str.split("#");
    4// result = ["Hello","World"]
    5
    6let result2 = str.split("");
    7// result2 = ["H","e","l","l","o","#","W","o","r","l","d"]

  • toLowerCase() / toUpperCase()


    toLowerCase() 함수는 문자열 안의 대문자를 모두 소문자로 바꾸고 toUpperCase() 함수는 문자열 안의 소문자를 모두 대문자로 바꾼다.


    1let str = "HELLO world";
    2
    3let result1 = str.toLowerCase();
    4// result1 = "hello world"
    5
    6let result2 = str.toUpperCase();
    7// result2 = "HELLO WORLD"

  • concat()


    1concat("합칠 문자열");

    concat() 함수는 합칠 문자열을 기존 문자열 뒤에 합치는 함수이다.


    1let str1 = "Hello";
    2let str2 = "World";
    3
    4let result = str1.concat(str2);
    5// reuslt = "Hello World"

  • trim()


    trim() 함수는 문자열 양쪽 끝 공백을 제거해주는 함수이다.


    1let str = " Hello World ";
    2let result = str.trim();
    3// result = "Hello World"

  • length


    length는 문자열의 전체 길이에 대한 속성값이다.


    1let str = "Hello";
    2let len = str.length; // len = 5
© 2023 by JONGMINFIRE.DEV. All rights reserved.
Theme by LekoArts