Real World JavaScript Part 4

Specifying a function as string replacement

In EmberJS camelize method is used for converting a string to its loweCamelCase form.

var STRING_CAMELIZE_REGEXP = /(\-|_|\.|\s)+(.)?/g; camelize: function(str) { return str.replace(STRING_CAMELIZE_REGEXP, function(match, separator, chr) { return chr ? chr.toUpperCase() : ''; }).replace(/^([A-Z])/, function(match, separator, chr) { return match.toLowerCase(); }); }

Much like using double quotes to define a string literal forward slashes / are used for defining a regular expression literal. Inside the regular expression (\-|_|\.|\s) is representative of (x) pattern and it means match x and then remember it.

Hyphen in regular expression is a special character and it is used to represent a range. If we place a backslah before hyphen, it will make the hyphen to be treated as a simple literal character instead. x|y pattern matches either x or y.

Dot . is also a special character and a backslash makes it an ordinary one. s is not a special character and a backslash before it makes it a special one. \s matches a single white space character, including space, tab, form feed, line feed. So (\-||\.|\s) is matching and remembering -,,., or a space character.

Next is a + and it means match the preceding character one or more times.

Next is (.)?. ., a special character means any character and the parentheses makes it to be remembered for later use. ? mark means match the preceding character zero or one time.

indiana_jones --> Matches _j indiana-jones --> Matches -j indiana.jones --> Matches .j indiana jones --> Matches j indiana______jones --> Matches ______j

The first parameter passed to the replacement function is the matched substring. Then the remembered groups are passed as parameters. Finally, offset and the entire string will be provided as the parameters. Behind the scenes, the function will be invoked and retrun value will be used as the replacement. This could be chained to avoid the usage of complicated regular expressions and to ease the function readiness.