Convert String Case in JavaScript with toUpperCase() and toLowerCase()
This Snippet is coded by a user inOnline javascript Compiler. You can see and run this code too.
زبان: JavaScript
The convertCase helper validates the input, then uses JavaScript’s built-in toUpperCase() or toLowerCase() methods to return a new string in the requested case. It accepts two inputs: a string to transform and a mode value, either "upper" or "lower". The output is the converted string, such as "HELLO, WORLD!" or "hello, world!". If the input is not a string, the function throws a TypeError; if the mode is invalid, it throws an Error. The original string remains unchanged because these built-in methods do not mutate strings. Each method processes every character in the input, so the time complexity is O(n), where n is the string length, and the space complexity is O(n) for the resulting string. For locale-sensitive casing, such as Turkish, consider toLocaleUpperCase() and toLocaleLowerCase() instead. This example is fully runnable in Node.js or any browser console.