Jul 16, 2010

JavaScript: escape()

When you're sending a string through a GET request with javascript, you should obviously URL encode the string to ensure all characters get transmitted. The escape() function in javascript works fairly well, even when you're sending UTF-8 characters. But the + character is interpreted as a space in the GET request, so you need to handle it manually. Here's how I do it:
 msg = msg.replace(/\+/g,'%2B'); 
 geturl('ajax.get.php?msg='+escape(msg));
First, you do a global regex match for the plus character, replace it with it's url encoded equivalent, and then you url encode the string with escape().

No comments: