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, "." )); |
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(); |
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(); |
THIS.IS.GEEKSFORGEEKS!