"Boldness has genius, power, and magic in it." - Johann Wolfgang von Goethe

JavaScript

[JS] JavaScript 문자데이터 정리

Toproot 2021. 7. 18. 18:23
728x90
728x90

 

🎃 JS 문자데이터

 

문자 데이터 종류

  • String: "", '', ``
  • Number
  • Boolean: true, false
  • undefined
  • null
  • Array: []
  • Object: {}

 

🎃 String - JavaScript/MDN

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

 

String - JavaScript | MDN

String 전역 객체는 문자열(문자의 나열)의 생성자입니다.

developer.mozilla.org

 

리터럴 : '' {} []

  • 기호를 통해서 데이터를 손쉽게 만드는 방법
  • 브라켓([ ]) 표기법을 사용하여 문자에 접근하는 경우 ,
  • 이러한 프로퍼티들에 새로운 값을 할당하거나 삭제할 수는 없습니다.
  • 포함되어 있는 프로퍼티들은 작성할 수도, 수정할 수도 없습니다.

 

메소드 string ≠ New String (object)

  • length : 길이 확인
  • +, += : 문자열 생성과 연결
  • IndexOf() : 서브문자열이 있는지 확인하고, 위치 확인
  • substring() : 서브 문자열(subString)을 추출
  • eval() : string으로 되어있는 숫자들을 계산해줌
  • valueOf() : String 오브젝트를 원형에 대응하도록 전환해줌

 

🎃 String - Method

 

String.prototype.indexOf()

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

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

 

String.prototype.indexOf() - JavaScript | MDN

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

developer.mozilla.org

 

// indexOf
// '' 리터럴로 문자데이터 생성
const result = 'Hello world'.indexOf('Heropy')
console.log(result)

// String.prototype.indexOf()
// 일치하는 값이 없으면 -1 반환
const str = '0123'

console.log(str.length) // 띄어쓰기도 개수로 카운팅

// 비교연산자를 사용해서 false 출력
const str = 'Hello world!'

console.log(str.indexOf('HEROPY') !== -1)

 

 

 

String.prototype.slice()
  • 메소드는 문자열의 일부를 추출하면서 새로운 문자열을 반환합니다.
const str = 'Hello world!'

console.log(str.slice(6, 11)) // world

 

String.prototype.replace()

  • replace() 메서드는 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환합니다.
  • 그 패턴은 문자열이나 정규식(RegExp)이 될 수 있으며,
  • 교체 문자열은 문자열이나 모든 매치에 대해서 호출된 함수일 수 있습니다.
const str = 'Hello world!'

console.log(str.replace('world', 'HEROPY'))



match (정규표현식)
  • 문자열이 정규식과 매치되는 부분을 검색합니다.
const str = 'abc@naver.com'

// 정규표현식(RegExp)
console.log(str.match(/.+(?=@)/))
//["abc", index: 0, input: "abc@naver.com", groups: undefined]

 

String.prototype.trim()

  • 메서드는 문자열 양 끝의 공백을 제거합니다.
  • 공백이란 모든 공백문자(space, tab, NBSP 등)와 모든 개행문자(LF, CR 등)를 의미합니다.
const str = '    Helo world      '

console.log(str.trim())

 

 

 

 

 

728x90
728x90