How to usea Regular Expression in Javascript
This approach utilizes a regular expression to match all uppercase letters in the string and replaces them with their lowercase equivalents using the replace()
function.
Example: Here, a custom function toLowerCaseRegex
is defined to convert the string to lowercase using a regular expression. The regular expression /[A-Z]/g
matches all uppercase letters in the string. The replace()
function is then used to replace each uppercase letter with its lowercase equivalent using a callback function (match => match.toLowerCase())
. This function is called with the originalString
variable, and the result is stored in lowercasedString
, which is then logged to the console.
Javascript
function toLowerCaseRegex(string) { return string.replace(/[A-Z]/g, match => match.toLowerCase()); } let originalString = "HeLLo WoRLD" ; let lowercasedString = toLowerCaseRegex(originalString); console.log(lowercasedString); // Output: "hello world" |
hello world
How to Lowercase a String in JavaScript ?
In JavaScript, converting a string to lowercase means transforming all the characters in the string to their lowercase equivalents. This operation is often used to ensure consistent comparison or formatting of text.
Below are the approaches used to Lowercase a string in JavaScript:
Table of Content
- Using the toLowerCase() Method
- Using a Custom Function with map() and toLowerCase()
- Using a Regular Expression