สมมติว่าเรามีสตริงที่ประกอบด้วยตัวอักษรภาษาอังกฤษบางตัวพิมพ์ใหญ่เช่นนี้ −
const str = "Connecting to server Connection has been successful We found result";
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงดังกล่าวและใส่เครื่องหมายจุลภาค ',' ก่อนเว้นวรรคก่อนตัวพิมพ์ใหญ่ทุกตัวในสตริง
รหัสสำหรับสิ่งนี้จะเป็น −
const str = "Connecting to server Connection has been successful We found
result";
const capitaliseNew = str => {
let newStr = '';
const regex = new RegExp(/.[A-Z]/g);
newStr = str.replace(regex, ',$&');
return newStr;
};
console.log(capitaliseNew(str)); ต่อไปนี้เป็นผลลัพธ์บนคอนโซล -
Connecting to server, Connection has been successful, We found result