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

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



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
Updated on: 2020-09-14T08:57:56+05:30

302 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements