Open In App

How to replace lowercase letters with an other character in JavaScript ?

Given a string and the task is to replace all lowercase letters from a string with the other characters in JavaScript. There are some approaches to replace the character that are described below:

JavaScript replace() Method: This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value. 



Syntax:

string.replace(searchVal, newvalue)

Parameters:



Return value: It returns a new string that matches the pattern specified in the parameters.

Example 1: This example replaces the lowercase letters with . (dot) using replace() method




var str = "WELCOMEiTOgGEEKS";
 
console.log(str.replace(/[a-z]/g, "."));

Output
WELCOME.TO.GEEKS

Example 2: This example replaces the lowercase letters with (‘ ‘)(space) by going to the each character and checking if it is lowercase. 




var str = "THISiISgGEEKSFORGEEKS!";
 
function gfg_Run() {
    let newStr = "";
 
    for (let i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) >= 97 &&
            str.charCodeAt(i) <= 122) {
            newStr += ' ';
        }
        else {
            newStr += str[i];
        }
    }
    console.log(newStr);
}
 
gfg_Run();

Output
THIS IS GEEKSFORGEEKS!

Example 3: In this example, we will use reduce method to replace all the lowerCase characters from string.




let str = "THISiISgGEEKSFORGEEKS!";
 
function check(x) {
    if (x >= 'a' && x <= "z") return false;
 
    return true;
}
 
function gfg_Run() {
    let newStr = [...str].reduce((accu, x) =>
        check(x) ? accu + x : accu + ".", '');
 
    console.log(newStr);
}   
 
gfg_Run();

Output
THIS.IS.GEEKSFORGEEKS!

Article Tags :