희락코딩

JavaScript_개념정리 / 문자열 / feat : 자주 사용하는 메서드 정리 본문

프로그래밍/자바스크립트 개념 정리

JavaScript_개념정리 / 문자열 / feat : 자주 사용하는 메서드 정리

Hello JoyCoding 2021. 4. 9. 01:53
728x90
반응형

문자열 / 자주 사용하는 메서드 정리


코딩을 하다보면 문자열 데이터를 다룰 일들이 많습니다. 이때 유용하고 효율적으로 사용하는 프로퍼티와 메소드에 대해 알아 보겠습니다.

 

 

1. String


▶  String() 에 전달 된 인자는 모두 문자열로 변환시켜주는 메서드 입니다.

 

String(7)   // '7'
String(false// 'false'
String([3,5,2,6])  // '3,5,2,6'

//반환된 값도 변경이 가능합니다.
const trueAnd = true && true
String(trueAnd)   // 'true'
String(false || true) // 'true' 

const fn = fucnction(){return 7}
String(fn)   //  '7'

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String

 

String - JavaScript | MDN

String String 전역 객체는 문자열(문자의 나열)의 생성자입니다.문자열 리터럴은 다음과 같은 형식을 사용합니다. 'string text' "string text" "中文 español Deutsch English देवनागरी العربية port

developer.mozilla.org

 

2. length


▶  length 는 문자열의 길이 즉, 문자 갯수를 반환해 줍니다.

 

'희락코딩'.length  // 4
'JoyCoding'.length // 9

//변수에 할당한 경우//
const str = '즐깁시다 코딩공부'
str.length;   //9

// 주의 !! 띄어쓰기도 길이를 포함합니다.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/length

 

String.length - JavaScript | MDN

String.length length 속성은 UTF-16 코드 유닛을 기준으로 문자열의 길이를 나타냅니다. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please c

developer.mozilla.org

 

3. indexOf


▶  indexOf() 는 인자로 전달된 문자열을 대상으로 한 문자열에서 검색하여 처음 발견된 곳의 index를 반환합니다. 발견하지 못한 경우 -1을 반환합니다.

 

const str = '코딩! 행복하게 즐기자' 

str.indexOf('코딩')  // 0
str.indexOf('')  // 9
str.indexOf('코피 난당!')  // -1

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

 

String.prototype.indexOf() - JavaScript | MDN

String.prototype.indexOf() indexOf() 메서드는 호출한 String 객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환합니다. 일치하는 값이 없으면 -1을 반환합니다.  The source for this interactive example is stor

developer.mozilla.org

 

4. substring


▶  substring()은 인자로 시작 인덱스와 끝 인덱스를 전달 시켜 그 시작 인덱스의 문자열과 끝 인덱스 전 까지의 문자열을 반환시켜 줍니다.

 

substring(start , end)

const
str = '코딩! 공부는 즐겁다!'

str.substring(0,3) // '코딩!'   
str.substring(6,4) // '공부'    //시작과 끝을 반대로 적어도 반환합니다.
str.substring(4) // '공부는 즐겁다!'  //end인덱스를 생략하면 start인덱스 기준으로 끝까지 반환합니다.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/substring

 

String.prototype.substring() - JavaScript | MDN

String.prototype.substring() substring()메소드는 string 객체의 시작 인덱스로 부터 종료 인덱스 전 까지 문자열의 부분 문자열을 반환합니다.  The source for this interactive example is stored in a GitHub repository. If yo

developer.mozilla.org

 

5. slice


▶  slice substring와 큰 차이는 없습니다. 다만 음수( - )를 전달받게 되면 뒤에서 인덱스를 접근합니다.

 

const str = '하루종일 앉아서 살쪘어염'

// 음수로 적용 할 경우 맨뒤 -1부터 0으로 인식합니다
str.slice(-4// '살쪘어염'

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/slice

 

String.prototype.slice() - JavaScript | MDN

String.prototype.slice() slice() 메소드는 문자열의 일부를 추출하면서 새로운 문자열을 반환합니다. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples p

developer.mozilla.org

 

6. replace


▶  replace()는 바꾸고 싶은 문자열이 있을때 문자열을 대체시키는 메소드입니다.

 

replace(변경전, 변경후

const
str = '코딩 공부 너무 짜증나'

str.replace('짜증나', '좋아요')    //  '코딩 공부 너무 좋아요'

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/replace

 

String.prototype.replace() - JavaScript | MDN

String.prototype.replace() replace() 메서드는 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환합니다. 그 패턴은 문자열이나 정규식(RegExp)이 될 수 있으며, 교체 문자열은

developer.mozilla.org

 

7. trim


▶ trim()은 문자열의 양쪽 끝 공백을 제거해줍니다.

 

const str = '      실수로 띄어쓰기를 했어염      '

str.trim()   //  '실수로 띄어쓰기를 했어염'

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

 

String.prototype.trim() - JavaScript | MDN

String.prototype.trim() trim() 메서드는 문자열 양 끝의 공백을 제거합니다. 공백이란 모든 공백문자(space, tab, NBSP 등)와 모든 개행문자(LF, CR 등)를 의미합니다. The source for this interactive example is stored in

developer.mozilla.org

 

8. split


split()은 인자로 전달된 값을 대상으로 한 문자열에서 검색해 전달 시켜준 값을 기준으로 분리시켜 문자열로 이루어진 배열을 반환하는 메소드입니다. immutability

 

const str = 'split메서드 꼭 기억 합시다!'

// 그냥 사용 할 경우 문자열을 배열로 반환합니다.
str.split()  // ["split메서드 꼭 기억 합시다!"]

// ''는 각 문자를 분리시켜 반환합니다.
str.split('') // ["s", "p", "l", "i", "t", "메", "서", "드", " ", "꼭", " ", "기", "억", " ", "합", "시", "다", "!"]

// ' '은 공백을 구분해서 각 단어를 반환합니다.
str.split(' ') // ["split메서드", "꼭", "기억", "합시다!"]

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/split

 

String.prototype.split() - JavaScript | MDN

String.prototype.split() split() 메서드는 String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눕니다. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interac

developer.mozilla.org

 

9. includes


includes()은 인자로 전달된 문자열을 대상으로 한 문자열에서 검색해서 참과 거짓을 반환해줍니다.

 

const str = '저는 코딩 공부를 끝까지 하겠습니다!'

str.includes('끝까지'// true
str.includes('포기할랭' // false

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/includes

 

String.prototype.includes() - JavaScript | MDN

String.prototype.includes() includes() 메서드는 하나의 문자열이 다른 문자열에 포함되어 있는지를 판별하고, 결과를 true 또는 false 로 반환합니다. The source for this interactive example is stored in a GitHub reposit

developer.mozilla.org

 

10. toUpperCase / toLowerCase


toUpperCase() / toLowCase()은 대상으로 한 문자열을 대문자 / 소문자로 변환 시켜줍니다.

 

const str = 'I Love coding'

str.toUpperCase()      //  "I LOVE CODING"
str.toLowerCase()      //  "i love coding"

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase

 

String.prototype.toUpperCase() - JavaScript | MDN

String.prototype.toUpperCase() toUpperCase() 메서드는 문자열을 대문자로 변환해 반환합니다. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, pleas

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase

 

String.prototype.toLowerCase() - JavaScript | MDN

String.prototype.toLowerCase() The toLowerCase() method returns the calling string value converted to lower case. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, ple

developer.mozilla.org

 

728x90
반응형
Comments