如何將所有大寫字母移動到 JavaScript 字串開頭?
比如說,我們的字串如下 −
my name is JOHN SMITH
使用 sort() 以及正則表示式 /[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
廣告