ไม่มีฟังก์ชัน built-in สำหรับแทนที่คำทุกครั้งที่ปรากฏ คุณต้องสร้างฟังก์ชันของตัวเอง
สมมติว่าต่อไปนี้คือสตริงของเรา:
var sentence = "Yes, My Name is John Smith. I live in US. Yes, My Favourite Subject is JavaScript";
ตัวอย่าง
var sentence = "Yes, My Name is John Smith. I live in US. Yes, My Favourite Subject is JavaScript";
console.log(sentence);
function replaceYesWithHi(word, sentence, replaceValue) {
return sentence.split(word).join(replaceValue);
}
var replacementofYesWithHi = replaceYesWithHi("Yes", sentence, "Hi");
console.log(replacementofYesWithHi);
เพื่อรันโปรแกรมข้างต้น ใช้คำสั่งต่อไปนี้:
node fileName.js.
ที่นี่ ชื่อไฟล์ของฉันคือ demo240.js
ผลลัพธ์
ผลลัพธ์มีดังนี้:
PS C:\Users\Amit\javascript-code> node demo240.js Yes, My Name is John Smith. I live in US. Yes, My Favourite Subject is JavaScript Hi, My Name is John Smith. I live in US. Hi, My Favourite Subject is JavaScript