Sunday, December 29, 2024
Google search engine
HomeLanguagesJavascriptHow to replace lowercase letters with an other character in JavaScript ?

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:

  • searchVal: It is a required parameter. It specifies the value or regular expression, that is going to replace by the new value.
  • newvalue: It is a required parameter. It specifies the value to be replaced by the search value.

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

Javascript




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. 

Javascript




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.

Javascript




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!
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments