Working With Strings

vancouver·2023년 6월 12일
0

javascript이해하기

목록 보기
15/22
post-custom-banner

Part 1

indexOf

const airline = `TAP Air Portugal`;
console.log(airline.indexOf(`r`)); // 6

lastIndexOf

const airline = `TAP Air Portugal`;
console.log(airline.lastIndexOf(`r`)); // 10

slice

console.log(airline.slice(4)); // Air Portugal (.slice(시작점))
console.log(airline.slice(4, 7)); // Air (.slice(시작점, 끝점))

new String

console.log(new String(`jang`)); 
/* String {'jang'}
0: "j"
1: "a"
2: "n"
3: "g"
length: 4
[[Prototype]]: String
[[PrimitiveValue]]: "jang" */
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`)); // 10
console.log(airline.indexOf(`portugal`)); // -1 (P와 p가 다름으로 -1은 false 뜻)

console.log(airline.slice(4)); // Air Portugal
console.log(airline.slice(4, 7)); // Air

console.log(airline.slice(0, airline.indexOf(` `))); // TAP
console.log(airline.slice(airline.lastIndexOf(` `) + 1)); // Portugal (+1 을 안하면  맨앞의 공백이 생김)

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(new String(`jang`)); 
/* String {'jang'}
0: "j"
1: "a"
2: "n"
3: "g"
length: 4
[[Prototype]]: String
[[PrimitiveValue]]: "jang" */

console.log(typeof new String(`jang`)); // object
console.log(typeof new String(`jang`).slice(1)); // string

Part 2

toLowerCase()

const passenger = `vAnCouVer`;
console.log(passenger.toLowerCase()) // vancouver

toUpperCase()

const passenger = `vAnCouVer`;
console.log(passenger.toUpperCase()) // VANCOUVER

trim()

const loginEmail = `   Hello@vancouver.io \n`;
console.log(loginEmail.trim())//'Hello@vancouver.io'

replace

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

includes

const plane = `Airbus A320neo`;
console.log(plane.includes(`A320`)); // true
console.log(plane.includes(`Boeing`)); // false
console.log(plane.includes(`Airb`)); // true

startsWith

const plane = `Airbus A320neo`;
plane.startsWith(`Airbus`) // true

endWith

const plane = `Airbus A320neo`;
plane.endWith(`neo`) // true

/ /g

정규표현식
door: 첫번째 door만 해당
/door/g: 모든 door 해당

const announcement = `All passengers come to boarding door 23. Boarding door 23!`;
console.log(announcement.replace(`door`, `gate`)); //All passengers come to boarding gate 23. Boarding door 23!
console.log(announcement.replace(/door/g, `gate`)); //All passengers come to boarding gate 23. Boarding gate 23!
// Fix capitalization in name
const passenger = `vAnCouVer`; // Vancouver
const passengerLower = passenger.toLowerCase();
const passengerCorrect =
  passengerLower[0].toUpperCase() + passengerLower.slice(1);
console.log(passengerCorrect); // Vancouver

// Comparing emails
const email = `hello@vancouver.io`;
const loginEmail = `   Hello@vancouver.io \n`;

// const lowerEmail = loginEmail.toLowerCase();
// const trimmedEmail = lowerEmail.trim();
// console.log(lowerEmail); //   hellow@vancouver.io
// console.log(trimmedEmail); //hello@vancouver.io

const normalizedEmail = loginEmail.toLowerCase().trim();
console.log(normalizedEmail); // hello@vancouver.io
console.log(email === normalizedEmail); // true

// replacing
const priceGB = `288,97₤`;
const priceUS = priceGB.replace(``, `$`).replace(`,`, `.`);
console.log(priceUS); // 288.97$

const announcement = `All passengers come to boarding door 23. Boarding door 23!`;

console.log(announcement.replace(`door`, `gate`)); //All passengers come to boarding gate 23. Boarding door 23!
console.log(announcement.replace(/door/g, `gate`)); //All passengers come to boarding gate 23. Boarding gate 23!

// Booleans
const plane = `Airbus A320neo`;
console.log(plane.includes(`A320`)); // true
console.log(plane.includes(`Boeing`)); // false
console.log(plane.includes(`Airb`)); // true

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

// 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 aboard!`);
  }
};

checkBaggage(`I have a laptop, some Food and a pocket Knife`); // You are NOT allowed on board
checkBaggage(`Socks and camera`); // Welcome aboard!
checkBaggage(`Got some snacks and a gun for protection`); // You are NOT allowed on board

Part 3

split

console.log(`a+very+nice+string`.split(`+`)); // (4) ['a', 'very', 'nice', 'string']
console.log(`Jonas Schmedtmann`.split(` `)); // (2) ['Jonas', 'Schmedtmann']

join

const [firstName, lastName] = `Jonas Schmedtmann`.split(` `);
const newName = [`Mr.`, firstName, lastName.toUpperCase()].join(` `);
console.log(newName); // Mr. Jonas SCHMEDTMANN

padding

padStart( ) , padEnd( ) (숫자까지 추가됨, 추가할 대상)

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

repeat

repeat(반복할 횟수)

const message2 = `Bad weather... All Departues Delayed... `;
console.log(message2.repeat(3)); /*Bad weather... All Departues Delayed... 
Bad weather... All Departues Delayed... Bad weather... All Departues Delayed... */
// Working With Strings Part-3

// Split and join
console.log(`a+very+nice+string`.split(`+`)); // (4) ['a', 'very', 'nice', 'string']
console.log(`Jonas Schmedtmann`.split(` `)); // (2) ['Jonas', 'Schmedtmann']

const [firstName, lastName] = `Jonas Schmedtmann`.split(` `);

const newName = [`Mr.`, firstName, lastName.toUpperCase()].join(` `);
console.log(newName); // Mr. Jonas SCHMEDTMANN

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 smith davis`);/* Jessica Ann Smith Davis 
                                             Jonas Schmedtmann */
capitalizeName(`jonas schmedtmann`);/* Jessica Ann Smith Davis
                                       Jonas Schmedtmann */

// Padding
const message = `Go to gate 23!`;
console.log(message.padStart(20, `+`).padEnd(30, `+`)); // ++++++Go to gate 23!++++++++++!
console.log(`Jang`.padStart(20, `+`).padEnd(30, `+`)); // ++++++++++++++++Jang++++++++++

const maskCreditCard = function (number) {
  const str = number + ``;
  const last = str.slice(-4);
  return last.padStart(str.length, `*`);
};

console.log(maskCreditCard(465498465132)); // ********5132
console.log(maskCreditCard(46549846565456)); // **********5456
console.log(maskCreditCard(46549841354656542)); // *************6540

// Repeat
const message2 = `Bad weather... All Departues Delayed... `;
console.log(message2.repeat(3)); /*Bad weather... All Departues Delayed... 
Bad weather... All Departues Delayed... Bad weather... All Departues Delayed... */

const planesInLine = function (n) {
  console.log(`There are ${n} planes in line ${``.repeat(n)}`);
};
planesInLine(5); // There are 5 planes in line ✈✈✈✈✈
planesInLine(3); // There are 3 planes in line ✈✈✈
planesInLine(12); // There are 12 planes in line ✈✈✈✈✈✈✈✈✈✈✈✈

Coding Challenge #4

// Coding Challenge #4
/* Write a program that receives a list of variable names written in underscore_case 
and convert them to camelCase. The input will come from a textarea inserted into the DOM 
(see code below to  insert the elements), and conversion will happen when the button is pressed.

/* underscore_case로 작성된 변수 이름 목록을 받아와서 camelCase로 변환하는 프로그램을 작성해보세요.
입력은 DOM에 삽입된 textarea에서 받아오며 (아래 코드를 참조하여 요소를 삽입하세요), 버튼이 눌렸을 때 변환이 수행됩니다. */

// 테스트 데이터 (텍스트 영역에 붙여넣기, 공백 포함):
/* underscore_case
   first_name
   Some_Variable 
   calculate_AGE
   delayed_departure */

//다음과 같은 출력을 생성해야 합니다 (콘솔에 별도의 5개의 출력):
/* underscoreCase ✅
   firstName ✅✅
   someVariable ✅✅✅
   calculateAge ✅✅✅✅
   delayedDeparture ✅✅✅✅✅ */

// Hints:
// 1. textarea에서 새 줄을 정의하는 문자를 기억하세요.

// 2. 해결책은 a_b와 같이 2개의 단어로 이루어진 변수에 대해서만 작동하면 됩니다.

// 3. 먼저 변수 이름 변환을 작동시키는 것에만 집중하세요. ✅에 대해 걱정하지 않아도 됩니다. 작업이 완료된 후에 처리하세요.
// 이 도전은 고난도로 의도된 것이므로, 도움이 필요한 경우 솔루션을 참조하고 멈추고 다시 진행하세요!

document.body.append(document.createElement("textarea"));
document.body.append(document.createElement("button"));

document.querySelector(`button`).addEventListener(`click`, function () {
  const text = document.querySelector(`textarea`).value;
  const rows = text.split(`\n`);
  console.log(rows);

  for (const [i, row] of rows.entries()) {
    const [first, second] = row.toLowerCase().trim().split(`_`);
    // console.log(row, first, second);

    const output = `${first}${second.replace(
      second[0],
      second[0].toUpperCase()
    )}`;

    console.log(`${output.padEnd(20)}${``.repeat(i + 1)}`);
  }
});

String Methods Practice

const flights = `_Delayed_Departure;fao93766109;txl2133758440;11:25
+_Arrival;bru0943384722;fao93766109;11:45
+_Delayed_Arrival;hel7439299980;fao93766109;12:05
+_Departure;fao93766109;lis2323639855;12:30`;

// 🔴 Delayed Departure from FAO to TXL (11h25)
//              Arrival from BRU to FAO (11h45)
//   🔴 Delayed Arrival from HEL to FAO (12h05)
//            Departure from FAO to LIS (12h30)
// ${type.startsWith(`Delayed`)}
const getCode = (str) => str.toUpperCase().slice(0, 3);

for (const flight of flights.split(`+`)) {
  const [type, from, to, time] = flight.split(`;`);
  const output = `${type.startsWith(`_Delayed`) ? `🔴` : ``} ${type.replaceAll(
    `_`,
    ` `
  )} from ${getCode(from)} ${getCode(to)} to (${time.replace(
    `:`,
    `h`
  )})`.padStart(46);
  console.log(output);
}
post-custom-banner

0개의 댓글