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

วิธีแทนที่อักขระที่ตำแหน่งเฉพาะใน JavaScript

String ใน JavaScript เป็น immutable (เปลี่ยนค่าไม่ได้) ต้องสร้าง string ใหม่

ตัวอย่าง: แทนที่ index 3

<html>
  <head>
    <title>JavaScript Boolean</title>
  </head>
  <body>
    <script>
      var str = "cric";
      document.write("Original String: " + str); // "cric"
      var index = 3;
      str = str.substr(0, index) + 'x' + str.substr(index + 1);
      document.write("<br>New String: " + str);   // "crix"
    </script>
  </body>
</html>

วิธีอื่นๆ (Modern)

ฟังก์ชัน reusable

function replaceAt(str, index, replacement) {
  if (index < 0 || index >= str.length) return str;
  return str.slice(0, index) + replacement + str.slice(index + replacement.length);
}

console.log(replaceAt("cric", 3, "x"));    // "crix"
console.log(replaceAt("hello", 2, "XX"));  // "heXXlo" (แทนที่ 1 char ด้วย 2 chars)

หมายเหตุ: substr() เป็น legacy ใช้ slice() หรือ substring() แทน

วิธีโค้ดหมายเหตุ
substring + concatstr.slice(0,i) + 'x' + str.slice(i+1)slice() แนะนำกว่า substr()
Array spread[...str].map((c,i)=>i===3?'x':c).join('')Functional style
Regex replacestr.replace(/./, 'x') (แค่ตัวแรก)ต้องใช้ regex advance สำหรับ index เฉพาะ