Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to move all capital letters to the beginning of the string in JavaScript?
To move all capital letters to the beginning of a string in JavaScript, we can use the sort() method with a regular expression to identify uppercase letters and rearrange them.
Let's say we have the following string:
my name is JOHN SMITH
We'll use sort() along with the 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 all capital letters at the beginning:");
console.log(moveAllCapitalLettersAtTheBeginning);
After moving all capital letters at the beginning: JOHNSMITHmynameis
How It Works
The solution uses the following approach:
-
Spread operator (
...): Converts the string into an array of individual characters - sort() method: Sorts the array based on a custom comparison function
-
Regular expression (
/[A-Z]/): Tests if a character is uppercase -
Comparison logic: Returns
-1to move uppercase letters before lowercase ones - join(''): Converts the sorted array back to a string
Alternative Method with Filter
Here's another approach using filter() to separate uppercase and lowercase characters:
function moveCapitalLettersToBeginning(str) {
const chars = [...str];
const uppercase = chars.filter(char => /[A-Z]/.test(char));
const lowercase = chars.filter(char => !/[A-Z]/.test(char));
return uppercase.join('') + lowercase.join('');
}
const result = moveCapitalLettersToBeginning('my name is JOHN SMITH');
console.log("Result:", result);
Result: JOHNSMITHmynameis
Preserving Spaces
If you want to preserve the original spacing, you can modify the approach:
function moveCapitalLettersPreserveSpaces(str) {
const chars = [...str];
const uppercase = chars.filter(char => /[A-Z]/.test(char));
const others = chars.filter(char => !/[A-Z]/.test(char));
return uppercase.join(' ') + ' ' + others.join('');
}
const result = moveCapitalLettersPreserveSpaces('my name is JOHN SMITH');
console.log("With preserved spacing:", result);
With preserved spacing: J O H N S M I T H my name is
Conclusion
Use the sort() method with regular expressions to rearrange string characters by case. The spread operator and join() help convert between strings and character arrays for easy manipulation.
