Reproducing Javascript’s escape() function in Groovy

June 9, 2011 at 4:21 pm 1 comment

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')}"
})
}

Advertisement

Entry filed under: Uncategorized. Tags: .

How to configure Notepad++ to always open in a new window

1 Comment Add your own

  • 1. dodger  |  December 13, 2011 at 12:13 pm

    ¡Great!

    You are a life saver!!

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


Categories

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 1 other follower


Follow

Get every new post delivered to your Inbox.