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

JavaScript มีเมธอดแทนที่ส่วนของสตริงโดยไม่สร้างสตริงใหม่หรือไม่

ใช่ สามารถใช้เมธอด replace() เพื่อแทนที่ส่วนของสตริงได้ (แม้ JavaScript จะเป็น Immutable แต่ replace() จะคืนค่าสตริงใหม่)

ไวยากรณ์

var anyVariableName = yourValue;
yourVariableName = yourVariableName.replace(yourOldValue, yourNewValue);

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

var message = "Hello, this is John";
console.log("Before replacing the message=" + message);

message = message.replace("John", "David Miller");
console.log("After replacing the message=" + message);

วิธีรันโปรแกรม

ใช้คำสั่ง node fileName.js (เช่น node demo57.js)

ผลลัพธ์

Before replacing the message=Hello, this is John
After replacing the message=Hello, this is David Miller