Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การทำซ้ำตัวอักษรในสตริง n ครั้ง - JavaScript

ฟังก์ชันนี้ทำซ้ำตัวอักษรทุกตัวในสตริง จำนวน n ครั้ง (รวมช่องว่างและสัญลักษณ์)

ตัวอย่าง

// Input: 'how are you', n = 2
// Output: 'hhooww  aarree  yyoouu'

ตัวอย่างโค้ด

const str = 'how are you';

const repeatNTimes = (str, n) => {
  let res = '';
  for (let i = 0; i < str.length; i++) {
    // ใช้ String.prototype.repeat()
    res += str[i].repeat(n);
  }
  return res;
};

console.log(repeatNTimes(str, 2));

วิธีทันสมัยกว่า

const repeatNTimes = (str, n) =>
  [...str].map(ch => ch.repeat(n)).join('');

ผลลัพธ์

hhooww  aarree  yyoouu

ประยุกต์ใช้: การสร้างข้อความตกแต่ง การทดสอบการเข้ารหัส การจัดรูปแบบข้อความ