» Javascript equivalent for PHP's get_html_translation_table

226 PHP equivalents

PHP to Javascript Project: php.js

php.jsThis article is part of the 'Porting PHP to Javascript' Project, which aims to decrease the gap between developing for PHP & Javascript.

A lot of people are familiar with PHP's functions, and though Javascript functions are often quite similar, some functions may be missing or addressed differently. The Javascript implementations should be as compliant with the PHP versions as possible, a good indication is that the PHP function manual could also apply to the Javascript version.

Porting crucial PHP functions to Javascript can be fun & useful. Currently some PHP functions have been added, but readers are encouraged to contribute and improve functions by adding comments. Eventually the goal is to save all the functions in one php.js file and make it publicly available for your coding pleasure.

If you choose to contribute, let me know how you want to be credited in the function's comments. You may also want to subscribe to RSS so you receive updates whenever new functions are posted.

This is a Javascript version of the PHP function: get_html_translation_table.

PHP get_html_translation_table

Description

get_html_translation_table - Returns the translation table used by htmlspecialchars() and htmlentities()

array get_html_translation_table([ int table [, int quote_style]] )

tableThere are two new constants (HTML_ENTITIES, HTML_SPECIALCHARS) that allow you to specify the table you want. Default value for table is HTML_SPECIALCHARS.

Parameters

  • table

    There are two new constants (HTML_ENTITIES, HTML_SPECIALCHARS) that allow you to specify the table you want. Default value for table is HTML_SPECIALCHARS.

  • quote_style

    Like the htmlspecialchars() and htmlentities() functions you can optionally specify the quote_style you are working with. The default is ENT_COMPAT mode. See the description of these modes in htmlspecialchars().

Return Values

Returns the translation table as an array.

See Also

Javascript get_html_translation_table

Source

This is the main source of the Javascript version of PHP's get_html_translation_table

function get_html_translation_table(table, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js. Meaning the constants are not
    // %          note: real constants, but strings instead. integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // %          note: Table from http://www.the-art-of-web.com/html/character-codes/
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    useTable      = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');
    useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
    
    // Map numbers to strings for compatibilty with PHP constants
    if (!isNaN(useTable)) {
        useTable = constMappingTable[useTable];
    }
    if (!isNaN(useQuoteStyle)) {
        useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];
    }
    
    if (useQuoteStyle != 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
 
    if (useQuoteStyle == 'ENT_QUOTES') {
        entities['39'] = '&#039;';
    }
 
    if (useTable == 'HTML_SPECIALCHARS') {
        // ascii decimals for better compatibility
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
        entities['38'] = '&amp;';
    } else if (useTable == 'HTML_ENTITIES') {
        // ascii decimals for better compatibility
      entities['60']  = '&lt;';
      entities['62']  = '&gt;';
      entities['160'] = '&nbsp;';
      entities['161'] = '&iexcl;';
      entities['162'] = '&cent;';
      entities['163'] = '&pound;';
      entities['164'] = '&curren;';
      entities['165'] = '&yen;';
      entities['166'] = '&brvbar;';
      entities['167'] = '&sect;';
      entities['168'] = '&uml;';
      entities['169'] = '&copy;';
      entities['170'] = '&ordf;';
      entities['171'] = '&laquo;';
      entities['172'] = '&not;';
      entities['173'] = '&shy;';
      entities['174'] = '&reg;';
      entities['175'] = '&macr;';
      entities['176'] = '&deg;';
      entities['177'] = '&plusmn;';
      entities['178'] = '&sup2;';
      entities['179'] = '&sup3;';
      entities['180'] = '&acute;';
      entities['181'] = '&micro;';
      entities['182'] = '&para;';
      entities['183'] = '&middot;';
      entities['184'] = '&cedil;';
      entities['185'] = '&sup1;';
      entities['186'] = '&ordm;';
      entities['187'] = '&raquo;';
      entities['188'] = '&frac14;';
      entities['189'] = '&frac12;';
      entities['190'] = '&frac34;';
      entities['191'] = '&iquest;';
      entities['192'] = '&Agrave;';
      entities['193'] = '&Aacute;';
      entities['194'] = '&Acirc;';
      entities['195'] = '&Atilde;';
      entities['196'] = '&Auml;';
      entities['197'] = '&Aring;';
      entities['198'] = '&AElig;';
      entities['199'] = '&Ccedil;';
      entities['200'] = '&Egrave;';
      entities['201'] = '&Eacute;';
      entities['202'] = '&Ecirc;';
      entities['203'] = '&Euml;';
      entities['204'] = '&Igrave;';
      entities['205'] = '&Iacute;';
      entities['206'] = '&Icirc;';
      entities['207'] = '&Iuml;';
      entities['208'] = '&ETH;';
      entities['209'] = '&Ntilde;';
      entities['210'] = '&Ograve;';
      entities['211'] = '&Oacute;';
      entities['212'] = '&Ocirc;';
      entities['213'] = '&Otilde;';
      entities['214'] = '&Ouml;';
      entities['215'] = '&times;';
      entities['216'] = '&Oslash;';
      entities['217'] = '&Ugrave;';
      entities['218'] = '&Uacute;';
      entities['219'] = '&Ucirc;';
      entities['220'] = '&Uuml;';
      entities['221'] = '&Yacute;';
      entities['222'] = '&THORN;';
      entities['223'] = '&szlig;';
      entities['224'] = '&agrave;';
      entities['225'] = '&aacute;';
      entities['226'] = '&acirc;';
      entities['227'] = '&atilde;';
      entities['228'] = '&auml;';
      entities['229'] = '&aring;';
      entities['230'] = '&aelig;';
      entities['231'] = '&ccedil;';
      entities['232'] = '&egrave;';
      entities['233'] = '&eacute;';
      entities['234'] = '&ecirc;';
      entities['235'] = '&euml;';
      entities['236'] = '&igrave;';
      entities['237'] = '&iacute;';
      entities['238'] = '&icirc;';
      entities['239'] = '&iuml;';
      entities['240'] = '&eth;';
      entities['241'] = '&ntilde;';
      entities['242'] = '&ograve;';
      entities['243'] = '&oacute;';
      entities['244'] = '&ocirc;';
      entities['245'] = '&otilde;';
      entities['246'] = '&ouml;';
      entities['247'] = '&divide;';
      entities['248'] = '&oslash;';
      entities['249'] = '&ugrave;';
      entities['250'] = '&uacute;';
      entities['251'] = '&ucirc;';
      entities['252'] = '&uuml;';
      entities['253'] = '&yacute;';
      entities['254'] = '&thorn;';
      entities['255'] = '&yuml;';
      entities['38']  = '&amp;';
    } else {
        throw Error("Table: "+useTable+' not supported');
        return false;
    }
    
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal)
        histogram[symbol] = entities[decimal];
    }
    
    return histogram;
}

Examples

Currently there is 1 example

Example 1

This is how you could call get_html_translation_table()
get_html_translation_table('HTML_SPECIALCHARS');
And that would return
{'"': '"', '&': '&', '<': '<', '>': '>'}

More about this Project

Download php.js

To easily include it in your code, every function currently available is stored in

Normal

Namespaced What is 'namespaced?'

To download use Right click, Save Link As
Generally the best way is to use a minified version and gzip it


Credits

Respect & awards go to everybody who has contributed in some way so far:

medalmedalOnno Marsman for contributing to:
 acos, acosh, asin, asinh, atan, atanh, ceil, cos, cosh, decbin, dechex, decoct, exp, floor, fmod, getrandmax, hypot, is_finite, is_infinite, is_nan, lcg_value, log, log10, max, max, min, min, mt_getrandmax, mt_rand, pi, pow, rand, round, sin, sinh, sqrt, tan, tanh, setcookie, preg_quote, addslashes, bin2hex, count_chars, html_entity_decode, htmlentities, htmlspecialchars_decode, levenshtein, ltrim, nl2br, nl2br, ord, parse_str, rtrim, soundex, str_ireplace, str_replace, str_replace, str_rot13, str_split, strcasecmp, strip_tags, stripos, stripslashes, stristr, strlen, strnatcmp, strncasecmp, strpbrk, strpos, strrev, strripos, strrpos, strstr, strtolower, strtoupper, substr, substr_count, trim, ucfirst, ucwords, base64_decode, empty, empty, is_array, is_bool, isset, utf8_decode, utf8_encode, utf8_encode
spacemedalBrett Zamir for contributing to:
 array_fill_keys, array_fill_keys, array_filter, array_merge, array_slice, array_splice, class_exists, method_exists, property_exists, call_user_func, call_user_func_array, func_get_arg, func_get_args, func_num_args, get_defined_functions, get_defined_functions, die, exit, str_split, strspn, get_defined_vars
spacemedalMichael White (link) for contributing to:
 array_count_values, get_included_files, include, include_once, require, require_once, md5, number_format, parse_str, printf, sha1, sprintf, str_pad, strnatcmp, http_build_query, floatval, is_object, print_r
spacemedalPaulo Ricardo F. Santos for contributing to:
 chunk_split, getdate, microtime, constant, define, chop, quotemeta, sprintf, get_headers, gettype, is_double, is_float, is_integer, is_long, is_scalar
spacemedalWaldo Malqui Silva for contributing to:
 array_fill, array_pad, array_product, array_rand, compact, count, range, abs, defined, ip2long, long2ip, implode, strcmp, ucwords
spacemedalJack for contributing to:
 compact, max, min, count_chars, htmlentities, md5, parse_str, soundex, sprintf, str_ireplace, strnatcmp, trim, utf8_encode
spacemedalJonas Raoni Soares Silva (link) for contributing to:
 shuffle, abs, setcookie, number_format, number_format, soundex, str_repeat, str_replace, str_rot13, ucwords, wordwrap, wordwrap
spacemedalPhilip Peterson for contributing to:
 sizeof, log10, round, echo, get_html_translation_table, nl2br, str_replace, strchr, urldecode, urlencode, var_export
spacemedalAtes Goral (link) for contributing to:
 array_change_key_case, array_count_values, array_diff_key, each, get_class, preg_quote, addslashes, count_chars, str_rot13, stripslashes
spacemedalLegaev Andrey for contributing to:
 end, reset, file, file_get_contents, function_exists, include, include_once, http_build_query, is_array, is_object
spacemedalMartijn Wieringa for contributing to:
 array_shift, array_unshift, str_ireplace, str_split, strcasecmp, stripos, strnatcmp, substr
spacemedalEnrique Gonzalez for contributing to:
 file_exists, filesize, decbin, decoct, deg2rad, rad2deg
spacemedalNate for contributing to:
 array_merge, array_sum, array_unique, addslashes, echo, strncasecmp
spacemedalPhilippe Baumann for contributing to:
 base_convert, bindec, dechex, hexdec, octdec, empty
spacemedalWebtoolkit.info (link) for contributing to:
 crc32, md5, sha1, utf8_decode, utf8_encode
 
spacemedalCarlos R. L. Rodrigues (link) for contributing to:
 array_chunk, array_unique, date, levenshtein
spacemedalJani Hartikainen for contributing to:
 file, file_exists, file_get_contents, filesize
spacemedalAsh Searle (link) for contributing to:
 basename, printf, sprintf
spacemedalErkekjetter for contributing to:
 ltrim, rtrim, trim
spacemedalGeekFG (link) for contributing to:
 krsort, ksort, time
spacemedalJohnny Mast (link) for contributing to:
 array_walk, array_walk_recursive, create_function
spacemedald3x for contributing to:
 array, explode, unserialize
spacemedalmarrtins for contributing to:
 array_change_key_case, addslashes, stripslashes
spacemedalAJ for contributing to:
 urldecode, urlencode
spacemedalAlex for contributing to:
 strip_tags, is_int
spacemedalAlfonso Jimenez (link) for contributing to:
 array_reduce, strpbrk
spacemedalAman Gupta for contributing to:
 base64_decode, utf8_decode
spacemedalArpad Ray (mailto:arpad@php.net) for contributing to:
 serialize, unserialize
spacemedalKarol Kowalski for contributing to:
 array_reverse, abs
spacemedalMirek Slugen for contributing to:
 htmlspecialchars, htmlspecialchars_decode
spacemedalSakimori for contributing to:
 strlen, wordwrap
spacemedalThunder.m for contributing to:
 base64_decode, base64_encode
spacemedalTyler Akins (link) for contributing to:
 base64_decode, base64_encode
spacemedalmdsjack (link) for contributing to:
 include, trim
spacemedal0m3r for contributing to:
 array_diff_assoc
spacemedalAlexander Ermolaev (link) for contributing to:
 trim
spacemedalAllan Jensen (link) for contributing to:
 number_format
spacemedalAndrea Giammarchi (link) for contributing to:
 array_map
spacemedalAndreas for contributing to:
 setcookie
spacemedalAndrej Pavlovic for contributing to:
 serialize
spacemedalAnton Ongson for contributing to:
 str_replace
spacemedalArno for contributing to:
 htmlspecialchars
spacemedalAtli Þór for contributing to:
 nl2br
spacemedalBayron Guevara for contributing to:
 base64_encode
spacemedalBen Bryan for contributing to:
 print_r
spacemedalBenjamin Lupton for contributing to:
 number_format
spacemedalBrad Touesnard for contributing to:
 date
spacemedalCagri Ekin for contributing to:
 parse_str
spacemedalCaio Ariede (link) for contributing to:
 strtotime
spacemedalChristian Doebler for contributing to:
 sleep
spacemedalCord for contributing to:
 is_array
spacemedalDavid for contributing to:
 is_numeric
spacemedalDavid James for contributing to:
 get_class
spacemedalDino for contributing to:
 serialize
spacemedalDouglas Crockford (link) for contributing to:
 gettype
spacemedalDxGx for contributing to:
 trim
spacemedalFGFEmperor for contributing to:
 mktime
spacemedalFelix Geisendoerfer (link) for contributing to:
 array_key_exists
spacemedalFrancesco for contributing to:
 empty
spacemedalFrancois for contributing to:
 htmlspecialchars_decode
spacemedalFremyCompany for contributing to:
 isset
spacemedalGabriel Paderni for contributing to:
 str_replace
spacemedalGaragoth for contributing to:
 serialize
spacemedalHoward Yeend for contributing to:
 number_format
spacemedalJ A R for contributing to:
 end
spacemedalKirk Strobeck for contributing to:
 strlen
spacemedalLH for contributing to:
 empty
spacemedalLeslie Hoare for contributing to:
 rand
spacemedalLincoln Ramsay for contributing to:
 basename
spacemedalLinuxworld for contributing to:
 bin2hex
spacemedalLuke Godfrey for contributing to:
 strip_tags
spacemedalManish for contributing to:
 is_array
spacemedalMarc Palau for contributing to:
 strip_tags
spacemedalMateusz "loonquawl" Zalega for contributing to:
 htmlspecialchars_decode
spacemedalMeEtc (link) for contributing to:
 date
spacemedalMick@el for contributing to:
 stripslashes
spacemedalNathan for contributing to:
 htmlspecialchars
spacemedalNick Callen for contributing to:
 wordwrap
spacemedalNorman "zEh" Fuchs for contributing to:
 utf8_decode
spacemedalOzh for contributing to:
 dirname
spacemedalPedro Tainha (link) for contributing to:
 unserialize
spacemedalPeter-Paul Koch (link) for contributing to:
 date
spacemedalPul for contributing to:
 strip_tags
spacemedalPyerre for contributing to:
 checkdate
spacemedalReverseSyntax for contributing to:
 htmlspecialchars_decode
spacemedalRobin for contributing to:
 is_nan
spacemedalSanjoy Roy for contributing to:
 array_diff
spacemedalSaulo Vallory for contributing to:
 strncasecmp
spacemedalScott Cariss for contributing to:
 htmlspecialchars_decode
spacemedalSimon Willison (link) for contributing to:
 str_replace
spacemedalSlawomir Kaniecki for contributing to:
 htmlspecialchars_decode
spacemedalSteve Clay for contributing to:
 function_exists
spacemedalSteve Hilder for contributing to:
 strcmp
spacemedalSteven Levithan (link) for contributing to:
 trim
spacemedalSubhasis Deb for contributing to:
 array_merge_recursive
spacemedalT. Wild for contributing to:
 filesize
spacemedal