JavaScript and special characters

Have you ever tried to include special characters like e.g. é, ê, è, or as a string into a JavaScript (like in an alert message when someone forgot to fill in a field in a form etc.)? Most likely it will look something like à followed by yet another character (especially in IE when the site is running on a Windows server, Firefox will probably get it right…). In order to avoid this you can simply replace the character with the corresponding Hex value (ASCII).

The following page “HTML Codes – Characters and symbols” provides a complete list of all Hex values. To insert the replacement code for the special character simply type \x followed by the value found under the Hex column. E.g. é equals \xE9.

If you are running PHP you can use the following function to generate the values:

function str2hex($str) {
    $res = "";
    $pre = mb_convert_encoding($str, 'UCS-2LE', 'UTF-8');
    for($i = 0; $i < strlen($pre); $i++) {
   		$res .= "\\x".strtoupper(bin2hex(substr($pre, $i, 1)));
	}
   	return str_replace('\\x00', '',$res);
}

Call the function by passing a string from e.g. a form like this:

<?php echo str2hex($_POST[someFormField]) ?>

As a result this “sentence”:

['é ê or è']

Will look like this:

\\x5B\\x27\\xE9\\x20\\xEA\\x20\\x6F\\x72\\x20\\xE8\\x27\\x5D

Usage

I believe this should come in handy for anyone that needs to provide text strings from a JavaScript (as an alert, prompt or whatever) running a multilingual site.

Feel free to comment should you have any questions or remarks.

About Author