Blogvaria

This page is brought to you by Blogvaria (http://blog.evaria.com).

To obtain more information, ask questions and interact please visit our website.

Back to Blogvaria landing page
Feedback
Subscribe
   
Blogvaria

 

The personal pages

JavaScript and special characters

TrackBack | Filed by Wennichen under Programming | Post popularity 4%

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.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • BlinkList
  • blogmarks
  • del.icio.us
  • De.lirio.us
  • digg
  • Furl
  • NewsVine
  • Netscape
  • Reddit
  • Spurl
  • SphereIt
  • Technorati
  • YahooMyWeb
  • DZone
  • feedmelinks
  • Linkter
  • Ma.gnolia
  • Slashdot
  • StumbleUpon
  • TailRank
  • co.mments

No comments yet.

Leave a Comment

Akismet has protected Blogvaria from 86,316 spam comments. Design by Evaria.com. Powered by WordPress.
Our beloved and trusted server has rendered 2.229 pages so far today, an amazing 4.328 pages yesterday
and even more astonishingly 167.946 pages since 30 November 2008 alone without dropping a byte nor a pixel.

Close
E-mail It