April 9, 2020
Estimated Post Reading Time ~

JavaScript: Replacing Logically using String:replace() method

When working with JavaScript, we might sometimes require to run some regEx on a string and replace its matches logically.
This can be easily done using the String:replace() method.
Lets Take an example to understand the concept: Suppose we want to write a function which converts the normal string to CamelCase String, then it can be implemented as:
Test Cases
  1. Input: “hello world”, Output: “helloWorld”
  2. Input: “Hello_world”, Output: “helloWorld”
Now lets write a function to satisfy the above test cases:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function toCamelCase(string){
   return string.replace( /((\w)[ _](\w))|(^(\w))/g,
    function( fullMatch,
                 spaceLetterSpace,
                 letterBeforeSpace,
                 letterAfterSpace,
                 startLetterAndCharacter, 
                 firstCharacter)
    {
        if(typeof spaceLetterSpace != 'undefined') return(letterBeforeSpace + letterAfterSpace.toUpperCase());
     
        if(typeof startLetterAndCharacter != 'undefined') return(firstCharacter.toLowerCase());
    })
}
Here what is happening is, if we pass a function in the second argument of .replace() function, then this function is executed against each match. Each group which is matched is passed in the argument. The first argument is the over all match and the further arguments are the matches corresponding to each group in the regular expression.


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.