Showing posts with label html encode. Show all posts
Showing posts with label html encode. Show all posts

Wednesday, 30 October 2013

Javascript snippet to HTML encode foreign characters

This Javascript snippet is useful for converting characters in a language like Arabic to HTML Encoding for putting on web pages.

var a = "السلام عليكم"; //Arabic for Peace Be Upon You (Hello)
var h = a.replace(/(.)/g, function($1){
   return ($1 == " ") ? $1 : "&#" + $1.charCodeAt() + ";";
});

The variable h now holds السلام عليكم
a.replace(/(.)/g, function($1){
  if ($1 == " ")
    return " ";
  else
    return "&#" + $1.charCodeAt() + ";";
})
"السلام عليكم"
"السلام عليكم"
"السلام عليكم"
"السلام عليكم"
console.log("السلام عليكم".replace(/(.)/g, function($1){
  if ($1 == " ")
    return " ";
  else
    return "&#" + $1.charCodeAt() + ";";
}));