I have the following line of coffeescript code (both dCnt and sDesc are jQuery objects), which does some basic cleaning up of a block of HTML while moving its location:
dCnt.append(sDesc.html().replace( /<div/gi, '<p' ).replace( /<\/div>/gi, '</p>' ).replace /\sstyle="text-align: center;"/gi, '')
This outputs the following JavaScript:
dCnt.append(sDesc.html().replace(/<div/gi, '<p').replace(/<\/div>/gi, '</p>').replace(/\sstyle="text-align: center;"/gi, ''));
The first two replaces cause no problems, but the third has taken a bit of work to come up with something the coffeescript compiler can cope with, and the result is too limiting and fragile for my liking.
So far I've discovered that:
1) If I have parenthesis () around the final replace then coffeescript interprets the double quotes as a string and gets confused (it ends up interpreting one of the forward slashes as a division).
2) If I remove the parenthesis that stops the MATH error, then it any white space in the regular expression will confuse the compiler - the output with white space instead of \s for the code above is (note the hideously broken parenthesis on the final replace):
dCnt.append(sDesc.html().replace(/<div/gi, '<p').replace(/<\/div>/gi, '</p>').replace / (style = "text-align: center;" / gi), '');
If the replace is not in a containing set of parenthesis (ie. remove the dCnt.append() from the code and handle that on a separate line) then white space in the regular expression will cause the compiler to throw an Unexpected ',' error (which is at least preferable to generating garbage JavaScript...).
Due to the need to remove the parenthesis (optional in coffeescript, although I find leaving them out seriously reduces code readability), it's not possible to chain two function calls which are afflicted by this issue.
Can anyone come up with a less fragile solution to this problem that still leaves the ability to use jQuery chaining intact?