[JS] working with strings

Hyodduru ·2021년 12월 14일
0

JavaScript

목록 보기
36/60
post-thumbnail

강의 출처 : The Complete JavaScript Course 2022 Jonas (Udemy)

Working With Strings - Part 1

IndexOf, lastIndexOf, slice

const airline = 'TAP Air Portugal';
const plane = 'A320';

console.log(plane[0]); //A;
console.log(plane[1]); //3;
console.log(plane[2]); //2;
console.log('B737'[0]); //B;
console.log(airline.length); // 16;
console.log('B737'.length); //4;

console.log(airline.indexOf('r')); //6
console.log(airline.lastIndexOf('r')); //6
console.log(airline.indexOf('Portugal')); //8

console.log(airline.slice(4));
console.log(airline.slice(4, 7)); //Air (7-4 3글자)

console.log(airline.slice(0, airline.indexOf(' '))); //TAP
console.log(airline.slice(airline.lastIndexOf(' ') + 1)); //Portugal

console.log(airline.slice(-2)); //al (뒤에서부터 가져옴)
console.log(airline.slice(1, -1)); //AP Air Portuga

const checkMiddleSeat = function (seat) {
  // B and E are middle seats
  const s = seat.slice(-1);
  if (s === 'B' || s === 'E') {
    console.log('You got the middle seat');
  } else {
    console.log('You got lucky');
  }
};

checkMiddleSeat('11B'); //You got the middle seat
checkMiddleSeat('23C'); //You got lucky
checkMiddleSeat('3E'); //You got the middle seat


console.log(typeof new String('jonas'));

모든 string object는 string을 return한다.

Working with strings - Part 2

toUpperCase(), toLowerCase(),trim()

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

//Fix capitalization in name
const passenger = 'joNas'; // need to fix to 'Jonas'
console.log(
  `${passenger.toUpperCase().slice(0, 1)}${passenger.toLowerCase().slice(1)}`
);
const passengerLower = passenger.toLowerCase();
const passengerCorrenct =
  passengerLower[0].toUpperCase() + passengerLower.slice(1);
console.log(passengerCorrenct);

//Comparing emails
const email = 'hello@jonas.io';
const loginEmail = ' Hello@Jonas.Io \n';

// const lowerEmail = loginEmail.toLowerCase();
// const trimmedEmail = lowerEmail.trim();
// console.log(trimmedEmail);

const normalizedEmail = loginEmail.toLowerCase().trim();
console.log(normalizedEmail);
console.log(email === normalizedEmail);

replace

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

const announcement =
  'All passengers come to boardng door 23. Boarding door 23!';

console.log(announcement.replace('door', 'gate')); // 오직 첫번째 door만 대체함;
console.log(announcement.replaceAll('door', 'gate')); // 모든 door 대체함

//+ regular expression
console.log(announcement.replace(/door/g, 'gate')); // g = global 모든 door대체

Booleans - includes(), startsWith(), endsWith()

const planes = 'Airbus A320neo';
console.log(planes.includes('A320')); //true
console.log(planes.includes('Boeing')); //false
console.log(planes.startsWith('Air')); //true

if (planes.startsWith('Airbus') && planes.endsWith('neo')) {
  console.log('Part of the NEW Aribus family');
} //Part of the NEW Aribus family

Practice exercise

먼저 다 lowercase로 바꿔주는 것 매우 중요!

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 aboard');
  }
};
checkBaggage('I have a laptop, some Food and a pocket Knife');
checkBaggage('Socks and camera');
checkBaggage('Got some snacks and a gun for protection');

Working with strings part 3

Split and Join

console.log('a+very+nice+string'.split('+')); // ['a', 'very', 'nice', 'string']
// 해당 seperater로 split 한 후 new array를 만들어낸다..
console.log('Jonas Schmedtnamm'.split(' ')); //['Jonas', 'Schmedtnamm']

const [firstName, lastName] = 'Jonas Schmedtnamm'.split(' ');

console.log(['Mr.', firstName, lastName.toUpperCase()].join(' ')); //Mr. Jonas SCHMEDTNAMM

const capitalizeName = function (name) {
  const names = name.split(' ');
  const namesUpper = [];

  for (const n of names) {
    //namesUpper.push(n[0].toUpperCase() + n.slice(1));
    namesUpper.push(n.replace(n[0], n[0].toUpperCase()));
  }
  console.log(namesUpper.join(' '));
};
capitalizeName('jessica ann simith davis');
capitalizeName('hyojeong kim');

Padding

const message = 'Go to gate 23';
console.log(message.padStart(20, '+').padEnd(30, '+')); //+++++++Go to gate 23++++++++++
console.log('Jonas'.padStart(20, '+').padEnd(30, '+')); //+++++++++++++++Jonas++++++++++

const maskCreditCard = function (number) {
  const str = number + '';
  const last = str.slice(-4);
  return last.padStart(str.length, '*');
};
console.log(maskCreditCard(123412341234)); //********1234
console.log(maskCreditCard('1234124214')); //******4214

Repeat

const message2 = 'Bad weater... All Departures Delayed...';
console.log(message2.repeat(5)); // 위의 message2 5번 반복됌 !

const planeInLine = function c(n) {
  console.log(`There are ${n} planes in line ${'✈️'.repeat(n)}`);
};
planeInLine(3); // There are 3 planes in line ✈️✈️✈️
planeInLine(7); // There are 7 planes in line ✈️✈️✈️✈️✈️✈️✈️
profile
꾸준히 성장하기🦋 https://hyodduru.tistory.com/ 로 블로그 옮겼습니다

0개의 댓글