logo
Published on

모던자바스크립트 32.String

Authors
  • avatar
    Name
    Bora Choi
    Twitter

String 생성자 함수

표준 빌트인 객체인 String 객체는 생성자 함수 객체다. 따라서 new 연산자와 함께 호출하여 String 인스턴스를 생성할 수 있다.

String 생성자 함수에 ~~인수를 전달~~하지 않고 new 연산자와 함께 호출하면 [[StringData]] 내부 슬롯에 빈 문자열을 할당String 래퍼 객체를 생성한다.

const strObj = new String()
console.log(strObj) //String {""}

String 생성자 함수의 인수로 문자열을 전달하면서 new 연산자와 함께 호출하면 [[StringData]] 내부 슬롯에 인수로 전달받은 문자열을 할당String 래퍼 객체를 생성한다.

const strObj = new String('Bora')
console.log(strObj)
// String {"Bora"}

String 생성자 함수의 인수로 문자열이 아닌 값을 전달하면 인수를 문자열로 강제 변환한 후 [[StringData]] 내부 슬롯에 변환된 문자열을 할당한 String 래퍼 객체를 생성한다.

new 연산자를 사용하지 않고 String 생성자 함수를 호출하면 string 인스턴스가 아닌 문자열을 반환한다.

length 프로퍼티

length 프로퍼티는 문자열의 문자 개수를 반환한다.

String 메서드

String 객체에는 원본 String 래퍼 객체를 직접 변경하는 메서드는 존재하지 않는다.

⇒ String 객체 메서드는 언제나 새로운 문자열을 반환한다.

문자열은 변경 불가능한 원시 값이기 때문에 String 래퍼 객체도 읽기 전용 read only 객체로 제공된다.

  • String 래퍼 객체가 읽기 전용이 아니라면 ?

    변경된 String 래퍼 객체를 문자열로 되돌릴때 문자열이 변경된다.

    따라서 String 객체의 모든 메서드는 String 래퍼 객체를 직접 변경할 수 없고, String 객체의 매서드는 언제나 새로운 문자열을 생성하여 반환한다.

String.prototype.indexOf

IndexOf 메서드는 대상 문자열에서 인수로 전달받은 문자열을 검색하여 첫 번째 인덱스를 반환한다. 검색에 실패하면 -1을 반환한다.

'Blue Whale'.indexOf('Blue') // returns  0
'Blue Whale'.indexOf('Blute') // returns -1
'Blue Whale'.indexOf('Whale', 0) // returns  5

String.prototype.search

인수로 전달받은 정규 표현식과 매치하는 문자열을 검색하여 일치하는 문자열의 인덱스를 반환한다. 검색에 실패하면 -1을 반환한다.

var str = 'hey JudE'
var re = /[A-Z]/g
var re2 = /[.]/g
console.log(str.search(re)) // returns 4, which is the index of the first capital letter "J"
console.log(str.search(re2)) // returns -1 cannot find '.' dot punctuation

String.prototype.includes

인수로 전달받은 문자열이 포함되어 있는지 확인하여 boolean 으로 반환한다.

var str = 'To be, or not to be, that is the question.'

console.log(str.includes('To be')) // true
console.log(str.includes('question')) // true

String.prototype.startsWith

대상 문자열이 인수로 전달 받은 문자열로 시작하는지 확인하여 그결과를 boolean 으로 반환한다. 2번째 인수로 검색을 시작할 인덱스를 전달할 수 있다.

var str = 'To be, or not to be, that is the question.'

console.log(str.startsWith('To be')) // true
console.log(str.startsWith('not to be'))

String.prototype.endsWith

대상 문자열이 인수로 전달 받은 문자열로 끝나는지 확인하여 그결과를 boolean 으로 반환한다. 2번째 인수로 검색을 시작할 문자열의 길이를 전달할 수 있다.

var str = 'To be, or not to be, that is the question.'

console.log(str.endsWith('question.')) // true
console.log(str.endsWith('to be')) // false
console.log(str.endsWith('to be', 19)) // true

String.prototype.charAt

인수로 전달받은 인덱스에 위치한 문자를 검색하여 반환한다. 문자열의 범위를 벗어난 정수인 경우 빈 문자열을 반환한다.

var anyString = 'Brave new world'
console.log("The character at index 0   is '" + anyString.charAt() + "'")
// No index was provided, used 0 as default

console.log("The character at index 0   is '" + anyString.charAt(0) + "'") //The character at index 0   is 'B'
console.log("The character at index 1   is '" + anyString.charAt(1) + "'") //The character at index 1   is 'r'
console.log("The character at index 2   is '" + anyString.charAt(2) + "'") //The character at index 2   is 'a'
console.log("The character at index 3   is '" + anyString.charAt(3) + "'") //The character at index 3   is 'v'
console.log("The character at index 4   is '" + anyString.charAt(4) + "'") //The character at index 4   is 'e'
console.log("The character at index 999 is '" + anyString.charAt(999) + "'") //The character at index 999 is ''

String.prototype.substring

첫번째 인수로 전달받은 인덱스에 위치하는 문자부터 두 번재 인수로 전달 받은 인덱스에 위치하는 문자의 바로 이전 문자까지의 부분 문자열을 반환한다.

var anyString = 'Mozilla'

// Displays 'M'
console.log(anyString.substring(0, 1))
console.log(anyString.substring(1, 0))

String.prototype.slice

substring메서드와 동일하게 동작한다. 음수인 인수를 전달하면 대상 문자열의 가장 뒤에서부터 시작하여 문자열을 잘라내어 반환한다.

var str1 = 'The morning is upon us.', // the length of str1 is 23.
  str2 = str1.slice(1, 8),
  str3 = str1.slice(4, -2),
  str4 = str1.slice(12),
  str5 = str1.slice(30)
console.log(str2) // OUTPUT: he morn
console.log(str3) // OUTPUT: morning is upon u
console.log(str4) // OUTPUT: is upon us.
console.log(str5) // OUTPUT: ""

String.prototype.toUpperCase

대상 문자열을 모두 대문자로변경한 문자열을 반환한다.

console.log('alphabet'.toUpperCase()) // 'ALPHABET'

String.prototype.toLowerCase

대상 문자열을 모두 소문자로변경한 문자열을 반환한다.

console.log('ALPHABET'.toLowerCase()) // 'alphabet'

String.prototype.trim

앞뒤에 공백 문자가 있을 경우 이를 제거한 문자열을 반환한다.

⇒ String.prototype.replace 메서드에 정규 표현식을 인수로 전달하여 공백 문자를 제거할 수도 있다.

var orig = '   foo  '
console.log(orig.trim()) // 'foo'

// 한 쪽의 공백만 제거하는 .trim() 예제

var orig = 'foo    '
console.log(orig.trim()) // 'foo'

String.prototype.repeat

대상 문자열을 인수로 전달받은 정수만큼 반복해 연결한 새로운 문자열을 반환한다. 0이면 빈문자열을 반환, 음수이면 RangeError를 발생시킨다. 인수를 생략하면 기본값 0이 설정된다.

'abc'.repeat(-1) // RangeError
'abc'.repeat(0) // ''
'abc'.repeat(1) // 'abc'
'abc'.repeat(2) // 'abcabc'
'abc'.repeat(3.5) // 'abcabcabc' (count will be converted to integer)
'abc'.repeat(1 / 0) // RangeError

String.prototype.replace

전달받은 문자열 또는 정규표현식을 검색하여 두 번째 인수로 전달한 문자열로 치환한 문자열을 반환한다.

검색한 문자열이 여럿 존재할 경우 첫 번째로 검색된 문자열만 친환한다.

특수한 교체패턴($&)을 사용할수 있다.

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?'

console.log(p.replace('dog', 'monkey'))
// "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

String.prototype.split

첫 번째 인수로 전달한 문자열 또는 정규표현식을 검색하여 문자열을 구분한 후 분리된 각 문자열로 이루어진 배열을 반환한다. 두 번째 인수로 배열의 길이를 지정할 수 있다.

var myString = 'Hello World. How are you doing?'
var splits = myString.split(' ', 3)

console.log(splits) //["Hello", "World.", "How"]

본 포스팅은 모던자바스크립트 deep dive를 공부하면서 정리한 내용입니다.