htmlEntities, array_search and strip_tags in JavaScript

Small post, small functions :-) Can be helpful for somebody someday.

htmlEntities, Array_search and strip_tags to Java Script (like PHP functions htmlEntities, array_search and strip_tags).

htmlEntities in Javascript

Sometimes you need convert all applicable characters to HTML entities, also in javascript. Very common use while working with Ajax.

A small diference of this function to php original function is the parameters and that, in this function, i change the original char to numeric entitie.

Example: in PHP htmlEntities, 'ã' will turn ã
In this function will turn ä

In both cases you will see 'ã' on browser. This can be very useful in Latin languages

function htmlEntities(texto){
    //by Micox - elmicoxcodes.blogspot.com - www.ievolutionweb.com
    var i,carac,letra,novo='';
    for(i=0;i<texto.length;i++){
        carac = texto[i].charCodeAt(0);
        if( (carac > 47 && carac < 58) || (carac > 62 && carac < 127) ){
            //se for numero ou letra normal
            novo += texto[i];
        }else{
            novo += "&#" + carac + ";";
        }
    }
    return novo;
}

Example:

document.getElementById('div_teste').innerHTML = htmlEntities('coração melão');

array_search in Javascript

Now array_search to javascript.

Searches the array for a given value and returns the corresponding key if successful.

function array_search(needle,haystack){
    //by Micox - elmicoxcodes.blogspot.com - www.ievolutionweb.com
    //ve se determinado valor existe no array e retorna sua chave
    for(var i in haystack){
        if(haystack[i]==needle){return i;}    
    }
    return false;
}

Example:

var where_is_pamela = array_search('pamela anderson', arr_hot_girls);

Strip tags in javascript

Continuing with strip_tags to javascript. This function is based in this post.

Strip HTML and PHP tags from a string;

function strip_tags($text){
 return $text.replace(/<\/?[^>]+>/gi, '');
}

 

Simple functions that can be useful someday. Thanks. Bye.

4 comments:

  1. Thank you, Thank you. I just used your strip tags function.

    ReplyDelete
  2. Referring to your html_entities function...I think it'be better to write it like I do:

    function(cadena) {

    var caracter = "";
    var cadenaProcesada = "";

    for(var i=0; i < cadena.length; i++)
    {
    caracter = cadena.charCodeAt(i);

    if( (caracter > 47 && caracter < 58) || (caracter > 62 && caracter < 127) )
    {
    cadenaProcesada += cadena[i];
    }
    else
    {
    cadenaProcesada += "&#" + caracter + ";";
    }
    }

    return cadenaProcesada;

    ReplyDelete
  3. function html_entity_decode(s) {
    //with prototype
    return new Element('textarea').update(s).innerHTML.replace('&','&');
    }

    ReplyDelete