สมมติว่าเรามีสตริงดังนี้:
var sentence = "My Name is David Miller I live in AUS";
เพื่อแทนที่ช่องว่างในสตริงข้างต้นด้วยขีดล่าง (_) ให้ใช้เมธอด split() ร่วมกับ join()
ตัวอย่างโค้ด
var sentence = "My Name is David Miller I live in AUS";
var withUnderscore = sentence.split(' ').join('_');
console.log("The actual result=");
console.log(sentence);
console.log("After replacing the space with underscore=");
console.log(withUnderscore);เพื่อรันโปรแกรม ใช้คำสั่ง:
node fileName.js
ที่นี่ชื่อไฟล์คือ demo250.js
ผลลัพธ์
จะได้ผลลัพธ์ดังนี้บนคอนโซล:
PS C:\Users\Amit\javascript-code> node demo250.js The actual result= My Name is David Miller I live in AUS After replacing the space with underscore= My_Name_is_David_Miller_I_live_in_AUS
คำอธิบายเพิ่มเติม: วิธีนี้ทำงานโดยแยกสตริงเป็นอาร์เรย์ด้วย split(' ') แล้วรวมกลับด้วย join('_') ซึ่งเป็นวิธีที่ง่ายและมีประสิทธิภาพสำหรับการแทนที่อักขระทั้งหมดในสตริง