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

การแทนที่ทุก n-th ตัวอักษรในสตริง - JavaScript

ฟังก์ชันนี้แทนที่ทุกครั้งที่เจอตัวอักษรตัวที่ n (nth occurrence) ของแต่ละตัวอักษร ด้วยตัวอักษรที่กำหนด

ตัวอย่าง

// Input: 'This is a sample string', n=2, char='*'
// Output: 'This ***a s*mple string'
// ทุกตัวอักษรที่ปรากฏครั้งที่ 2 จะถูกแทนที่ด้วย *

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

const str = 'This is a sample string';
const num = 2;
const char = '*';

const replaceNthAppearance = (str, num, char) => {
  const creds = str.split('').reduce((acc, val, ind, arr) => {
    let { res, map } = acc;

    if (!map.has(val)) {
      map.set(val, 1);
      if (num === 0) {
        res += char;
      } else {
        res += val;
      }
    } else {
      const freq = map.get(val);
      if (num - freq === 1) {
        res += char;
      } else {
        res += val;
      }
      map.set(val, freq + 1);
    }
    return { res, map };
  }, { res: '', map: new Map() });

  return creds.res;
};

console.log(replaceNthAppearance(str, num, char));

การทำงาน

  • ใช้ Map นับจำนวนครั้งที่เจอแต่ละตัวอักษร
  • ตอนเจอครั้งที่ num → ใส่ char แทน
  • นับแยกตามตัวอักษร (แต่ละตัวอักษรมีตัวนับของตัวเอง)

ผลลัพธ์

This ***a s*mple string