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

การแทนที่ตัวอักษรครั้งที่ n ในสตริงด้วย JavaScript

ภาพรวม

บทความนี้สาธิตวิธีแทนที่ตัวอักษรที่ปรากฏครั้งที่ n ในสตริงด้วยตัวอักษรที่กำหนด

ตัวอย่าง

Input:  str='This is a sample string', n=2, char='*'
Output: 'This ***a s*mple string'
// ตัวอักษรที่ปรากฏครั้งที่ 2: i(2nd), s(2nd), a(2nd), m(2nd), p(2nd), l(2nd), e(2nd)
// ทั้งหมดถูกแทนที่ด้วย *

การนำไปใช้

const replaceNthAppearance = (str, num, char) => {
  const creds = [...str].reduce((acc, val, ind, arr) => {
    let { res, map } = acc;
    
    if (!map.has(val)) {
      map.set(val, 1);
      res += (num === 0 ? char : val); // n=0 แทนที่ตัวแรก
    } else {
      const freq = map.get(val);
      if (num - freq === 1) { // ครั้งที่ n
        res += char;
      } else {
        res += val;
      }
      map.set(val, freq + 1);
    }
    return { res, map };
  }, { res: '', map: new Map() });
  
  return creds.res;
};

console.log(replaceNthAppearance('This is a sample string', 2, '*'));

ผลลัพธ์

This ***a s*mple string

วิธีที่เข้าใจง่ายกว่า

const replaceNthOccurrence = (str, n, replacement) => {
  if (n <= 0) return str;
  
  const counts = new Map();
  let result = '';
  
  for (const char of str) {
    const count = (counts.get(char) || 0) + 1;
    counts.set(char, count);
    
    result += (count === n) ? replacement : char;
  }
  
  return result;
};

การขยาย: แทนที่เฉพาะตัวอักษรบางตัว

const replaceNthOfTarget = (str, targetChar, n, replacement) => {
  let count = 0;
  return [...str].map(c => {
    if (c === targetChar) {
      count++;
      return count === n ? replacement : c;
    }
    return c;
  }).join('');
};

console.log(replaceNthOfTarget('hello world', 'l', 2, 'X')); // heXlo world

การประยุกต์ใช้

  • Text Obfuscation / Watermarking
  • String Transformation Pipelines
  • Game: Typing Effects
  • Data Anonymization

ข้อควรระวัง

  • n=0: โค้ดต้นฉบับแทนที่ตัวแรก (Logic แปลก)
  • n > Max Occurrences: ไม่มีการแทนที่
  • Unicode: ใช้ [...str] สำหรับ Emoji/Thai
  • Case Sensitivity: 'A' != 'a'