โจทย์
String: ' my name is JOHN SMITH '
ย้ายตัวอักษรพิมพ์ใหญ่ทั้งหมดไปต้น string
วิธีทำ
ใช้ sort() ร่วมกับ regex /[A-Z]/
ตัวอย่างโค้ด
var moveAllCapitalLettersAtTheBeginning = [...' my name is JOHN SMITH ']
.sort((value1, value2) => /[A-Z]/.test(value1) ? /[A-Z]/.test(value2) ? 0 : -1 : 0)
.join(' ');
console.log("After moving the all capital letters at the beginning=");
console.log(moveAllCapitalLettersAtTheBeginning);
วิธีรัน
node fileName.js
ชื่อไฟล์ demo199.js
ผลลัพธ์
PS C:\Users\Amit\javascript-code> node demo199.js After moving the all capital letters at the beginning= J O H N S M I T H m y n a m e i s
คำอธิบาย
[...str] spread string เป็น array ของ characterssort() ใช้ comparator function:
- ถ้า value1 เป็น uppercase (test true) และ value2 เป็น uppercase → 0 (คงลำดับ)
- ถ้า value1 uppercase, value2 ไม่ใช่ → -1 (value1 ไปก่อน)
- กรณีอื่น → 0join(' ') รวมกลับเป็น string คั่น space