Reproducing Javascript’s escape() function in Groovy

From time to time, I’ve seen people looking for a way to reproduce Javascript’s escape() function in this or that language. It’s not a complex function – escape() simply replaces characters that aren’t alphanumeric (and a few symbols) with their Unicode values in hexadecimal. Anyway, I recently had a need to escape something using Groovy. Here’s the method.


/* A method to mimic Javascript's escape() function.
* It replaces 'special characters' with their Unicode hexadecimal
* equivalent. This simple method is not designed to handle
* double byte character sets. Feel free to improve it.
*/
String escapeLikeJavascript(String sourceText) {
def specialCharsRegex = /[^\w@*-+.\/]/
return sourceText.replaceAll(specialCharsRegex, {
"%${Integer.toHexString(it.codePointAt(0)).toUpperCase().padLeft(2, '0')}"
})
}

Advertisements