JavaScript: Replacing Logically using String:replace() method

25 / Sep / 2012 by Kushal Likhi 0 comments

Hi,

 

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:
[js]
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());

})
}
[/js]
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.

 

 

Hope it Helps!
Kushal Likhi

FOUND THIS USEFUL? SHARE IT

Tag -

javascript

Leave a Reply

Your email address will not be published. Required fields are marked *