How to move all capital letters to the beginning of the string in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say following is our string −

my name is JOHN SMITH

Use sort() along with regular expression /[A-Z]/ to move all capital letters to the beginning of the string/

Example

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);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo199.js.

Output

This will produce the following output −

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
raja
Published on 14-Sep-2020 08:57:33
Advertisements