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
Change string based on a condition - JavaScript
We are required to write a JavaScript function that takes in a string. The task of our function is to change the string according to the following condition ?
- If the first letter in the string is a capital letter then we should change the full string to capital letters.
- Otherwise, we should change the full string to small letters.
Example
Following is the code ?
const str1 = "This is a normal string";
const str2 = "thisIsACamelCasedString";
const changeStringCase = str => {
let newStr = '';
const isUpperCase = str[0].charCodeAt(0) >= 65 && str[0].charCodeAt(0) <= 90;
if(isUpperCase){
newStr = str.toUpperCase();
}else{
newStr = str.toLowerCase();
};
return newStr;
};
console.log(changeStringCase(str1));
console.log(changeStringCase(str2));
Output
Following is the output in the console ?
THIS IS A NORMAL STRING thisisacamelcasedstring
Alternative Method Using Regular Expressions
We can also use regular expressions to check if the first character is uppercase:
const changeStringCaseRegex = str => {
return /^[A-Z]/.test(str) ? str.toUpperCase() : str.toLowerCase();
};
console.log(changeStringCaseRegex("Hello World"));
console.log(changeStringCaseRegex("hello world"));
console.log(changeStringCaseRegex("JavaScript"));
HELLO WORLD hello world JAVASCRIPT
How It Works
The solution uses ASCII values to check if the first character is uppercase. ASCII values for uppercase letters A-Z range from 65 to 90. If the first character falls in this range, the entire string is converted to uppercase using toUpperCase(). Otherwise, it's converted to lowercase using toLowerCase().
The regex alternative /^[A-Z]/ matches if the string starts with an uppercase letter, providing a more concise solution.
Conclusion
Both methods effectively check the first character's case and transform the entire string accordingly. The regex approach is more concise, while the ASCII method provides better understanding of character codes.
