Bermain Dengan String - JavaScript

boibolang

boibolang

Posted on January 20, 2024

Bermain Dengan String - JavaScript

String adalah karakter atau kumpulan karakter. Operasi yang melibatkan string mirip dengan array, oleh karenanya ada beberapa fungsi manipulasi array yang bisa dipergunakan untuk string. Semua operasi string akan mengembalikan nilai string tapi tidak merubah string asal, jadi kita harus menyimpan nilai baru kedalam variabel.

Mengambil nilai string.

const airlines = 'AMERICAN AIRLINES INC.';
const plane = 'AA212';

console.log(airlines[0]); // output: A
console.log('AA212'[0]); // output: A
console.log(airlines.slice(4, 9)); // mulai dari index ke-4 dan berhenti sebelum index ke-9, output: ICAN
console.log(airlines.slice(0, airlines.indexOf(' '))); // output: AMERICAN(spasi)
console.log(airlines.slice(airlines.lastIndexOf(' ') + 1)); // output: INC.
console.log(airlines.slice(-2)); // mengambil 2 karakter terakhir, output: C
console.log(airlines.slice(1, -3)); // mulai dari index ke-1 dan berhenti sebelum 3 karakter terakhir, output: MERICAN AIRLINES I
Enter fullscreen mode Exit fullscreen mode

Huruf kapital.

/ (string).toLowerCase() dan (string).toUpperCase()
const passenger = 'haRRY POtter';
const lower = passenger.toLowerCase();
const upper = passenger.toUpperCase();
console.log(lower, upper); // output: harry potter HARRY POTTER
Enter fullscreen mode Exit fullscreen mode

Mengganti nilai string.

// (string).replace()
const priceGb = '100,87£';
const priceUS = priceGb.replace('£', '$').replace(',', '.');
console.log(priceUS); // output: 100.87$

// (string).replace() hanya mengganti kata/karakter pertama yang ditemukan, jika ingin mengganti seluruh kata/karakter gunakan (string).replaceAll()
const str1 = 'Saya akan pergi ke toko sepatu, setelah itu ke toko daging';
console.log(str1.replace('toko', 'tukang'));
console.log(str1.replaceAll('toko', 'ahli'));
Enter fullscreen mode Exit fullscreen mode

result

Boolean.

const nama1 = 'Carlos Gracie';
console.log(nama1.includes('Gracie'));
if (nama1.endsWith('Gracie')) {
  console.log('Part of Gracie family'); // output: Part of Gracie Family
}
Enter fullscreen mode Exit fullscreen mode

Split dan join.

console.log('Eustass Kid'.split(' '));
const [firstname, lastName] = 'Eustass Kid'.split(' ');
const newName = ['Mr.', firstname, lastName.toUpperCase()].join(' ');
console.log(newName);

const capitalName = function (name) {
  const pass = name.toLowerCase().split(' ');
  const upper = [];
  for (const n of pass) {
    upper.push(n.replace(n[0], n[0].toUpperCase()));
  }
  console.log(upper.join(' '));
};
capitalName('andrEW SmiTh');
capitalName('GEORge wasHingTON bUSH');
Enter fullscreen mode Exit fullscreen mode

result

Padding.
padStart: menambahkan karakter awal sebanyak sisa string.
padEnd: menambahkan karakter akhir sebanyak sisa string.

console.log('Go to gate 23'.padStart(25, '+').padEnd(35, '-'));
console.log('Boy Sandra'.padStart(25, '+').padEnd(35, '-'));
Enter fullscreen mode Exit fullscreen mode

result

Repeat.

const message = 'This is a drill, please remain calm...';
console.log(message.repeat(3));
Enter fullscreen mode Exit fullscreen mode

result

Contoh penggunaan string, semisal kita memiliki data penerbangan dalam bentuk karakter sebagai berikut:
'_Delayed_Departure;fao93766109;txl2133758440;11:25+_Arrival;bru0943384722;fao93766109;11:45+_Delayed_Arrival;hel7439299980;fao93766109;12:05+_Departure;fao93766109;lis2323639855;12:30';

Kita ingin data tersebut bisa dibaca dengan semestinya, berikut adalah kode program yang bisa kita pakai:

const getCode = (str) => str.slice(0, 3).toUpperCase();
for (const flight of flights.split('+')) {
  const [type, from, to, time] = flight.split(';');
  const output = `${type.startsWith('_Delayed') ? '😒' : ''}${type.replaceAll(
    '-',
    ''
  )} ${getCode(from)} ${getCode(to)} (${time.replace(':', 'h')})`.padStart(36);
  console.log(output);
}
Enter fullscreen mode Exit fullscreen mode

result

💖 💪 🙅 🚩
boibolang
boibolang

Posted on January 20, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024

Modern C++ for LeetCode 🧑‍💻🚀
leetcode Modern C++ for LeetCode 🧑‍💻🚀

November 29, 2024