타닥타닥 개발자의 일상

[JS/자바스크립트] 문자열을 소문자 변환, 대문자 변환, 자르기, 교체하기 하는 방법 본문

코딩 기록/JavaScript

[JS/자바스크립트] 문자열을 소문자 변환, 대문자 변환, 자르기, 교체하기 하는 방법

NomadHaven 2023. 6. 9. 21:50

자바스크립트는 문자열을 편집하는 다양한 메서드를 제공한다.

해당 메서드는 무척 유용한 게 많아서 잘 알아두면 나중에 큰 도움이 될 것이다.

 

그렇다면 문자열 string 을 편집하는 메서드는 무엇이있는지 알아보자.

 

 

문자열을 대소문자로 변환하는 기능
const airline = 'TAP Air Portugal';

console.log(airline.toLowerCase()); //tap air portugal
console.log(airline.toUpperCase()); //TAP AIR PORTUGAL
console.log('nomad'.toUpperCase());

.toLowerCase() 메서드를 이용하면 문자열을 한번에 소문자로 바꾸는 게 가능하다

.toUpperCase() 메서드를 이용하면 문자열을 한번에 대문자로 바꾸는 게 가능하다.

 

출력화면

tap air portugal
TAP AIR PORTUGAL
NOMAD

 

 

그렇다면 위의 기능을 종합하여 첫번째 글자는 대문자, 그 이후 글자는 소문자로 맞추는 조정도 가능할까?

물론 가능하다.

 

const passenger = 'nOmaD'; 
const passengerLower = passenger.toLowerCase();
const passengerCorrect =
  passengerLower[0].toUpperCase() + passengerLower.slice(1);

console.log(passengerCorrect); //Nomad 로 교정

1.문자열을 모두 소문자로 toLowerCase 메서드를 통해서 모두 소문자로 교체

2. 교체된 문자열의 0번째 인덱스 문자를 toUpperCase 메서드를 이용해서 대문자로 교체, 1번째 인덱스 이후의 문자열 slice 메서드로 자르기(1번째 인덱스 문자열 포함) 해서 두 문자열 +로 결합

 

출력화면
Nomad

 

 

 

 


 

문자열 비교하기
//Comparing email
const email = 'hello@nomad.io';
const loginEmail = '  Hello@nomad.Io \n';
const normalizedEmail = loginEmail.toLowerCase().trim();

console.log(normalizedEmail); //hello@nomad.io
console.log(email === normalizedEmail); //true

변수 email의 문자열과

loginEmail의 문자열은 다르다.

 

하지만 loginEmail의 문자열을 toLowerCase 메서드로 소문자 변환 후, trim 메서드를 통해 공백을 삭제한 뒤 normalizaedEmail 변수에 넣는다면?

 

normalizedEmail 변수는 결과적으로 email 변수의 문자열과 같게된다.

따라서 email === normalizedEmail 을 비교하면 true 가 출력된다.

 

hello@nomad.io
true

 

 

해당 문자열에 특정 단어가 있는지 확인하고 싶을댄 includes 메서드를 사용하면 된다.

includes('특정단어')를 입력해서 출력하면, 해당 단어가 있을시 true 아닐시 false가 나온다.

//Booleans
const plane = 'Airbus A320neo';
console.log(plane.includes('A320')); //true
console.log(plane.includes('Boeing')); //false
출력화면
 true
 false

 

만약 특정 위치에 특정 문자열이 있는지 알고 싶다면 startsWith 메서드와 endsWith 메서드를 사용하면 된다.

해당 문자열이 특정 문자열로 시작하는지 알고 싶을 때 쓰는 문자열은 startsWtih이고

해당 문자열이 특정 문자열로 끝나는지 알고 싶을 때 쓰는 문자열은 endsWith이다.

 

const plane = 'Airbus A320neo';
console.log(plane.startsWith('Air')); //true
console.log(plane.startsWith('Airb')); //true
console.log(plane.startsWith('bus')); //false

if (plane.startsWith('Airbus') && plane.endsWith('neo')) {
  console.log('Part of the New Airbus Family');
}



출력화면
true
true
false
Part of the New Airbus Family

 

 


 

 

문자열 교체하기

특정 문자열에서 일부만 변경하고 싶을때가 있다.

그럴때는 replace 메서드를 쓰면 좋다.

replace('바꾸고 싶은 문자열','교체할 문자열') 과 같은 순서로 코드를 작성하면 된다.

 

//replacing
const priceGB = '288,97F';
const priceUS = priceGB.replace('F', '$').replace(',', '.');
console.log(priceUS);

예를 들어 288,97F는 영국의 파운드 화폐 단위를 표현한 문자열이다.

이 문자를 미국의 달러 단위로 바꾸고자 한다면 288.97$가 될수있다.

원래 문자열에서 ','와'F' 만 바꾸면 될 일이다.

이때 쓰는게 replace 메서드다.

출력화면
288.97$

 

 

위의 예시 문장처럼 띄워쓰기 없이 붙어있는 문자열만 되는게 아니라,

공백이 있는 긴 문장역시 교체가 가능하다는 점이 replace 메서드의 장점이다.

 

 

const announcement =
  'All passengsers come to boarding door 23. Boadring door 23!';

console.log(announcement.replace('door', 'gate')); //오로지 첫번째 단어만 바꿔줌
console.log(announcement.replaceAll('door', 'gate')); //모든 단어가 바뀜
console.log(announcement.replaceAll(/door/g, 'gate')); //모든 단어가 바뀜. g는 global

참고로 replace 메서드를 쓰면 바꾸고자 하는 문자열의 첫번째 단어만 바뀐다. 그 뒤에 변환하고자 하는 단어가 나와도 이미 첫번째 단어가 바껴서 더이상 바뀌지 않는다.

 

그래서 console.log(announcement.replace('door', 'gate')); 를 출력하면

All passengsers come to boarding gate 23. Boadring door 23!

와 같이 첫번째 door만 gate로 변경되며, 두번때 door은 그대로 남아있는다.

 

만약 모든 단어를 교체하고 싶다면 replace대신 repalceAll을 쓰면 된다.

 

console.log(announcement.replaceAll('door', 'gate')); 를 출력하면

All passengsers come to boarding gate 23. Boadring gate 23!

와 같이 모든 door이 gate라는 단어로 바뀐다.

 

만약 replace를 쓰는 대신에 모든 단어를 바꾸고 싶다면?

바꾸고 싶은 단어 앞뒤를 슬래쉬(/)로 감싸고 g를 붙여주면 된다. g는 global이라는 뜻으로 모든 단어를 광역적으로 바꾸겠다는 의미이다.

 

 

console.log(announcement.replaceAll(/door/g, 'gate')); 를 출력하면

 

All passengsers come to boarding gate 23. Boadring gate 23!

replace를 썼음에도 불구하고 모든 door가 gate로 바뀐걸 알 수 있다.

 

 

 

 

위에서 다룬 내용을 조합해서 간단한 함수를 만들수 있다.

 

bagge에 knife와 gun이 포함되면 탑승할수 없다는 메세지를 출력하는 함수를 만든다고 해보자.

우선 문자열을 toLowerCase 메서드를 이용해서 모두 소문자로 만든 뒤,

includes 메서드로 찾고자 하는 문자열을 걸러내면  된다.

 

//Practice Exercise
const checkBaggage = function (items) {
  const baggage = items.toLowerCase();
  if (baggage.includes('knife') || baggage.includes('gun')) {
    console.log('You are not allowed on board');
  } else {
    console.log('Welcome abroad');
  }
};

checkBaggage('I have a laptop, some Food and a pocket Knife');
checkBaggage('socks and camera');
checkBaggage('Got some snacks and a gun for proctection');
출력화면
You are not allowed on board
Welcome abroad
You are not allowed on board

 

Comments