SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Evangelist winterheat's Avatar
    Join Date
    Aug 2007
    Posts
    508
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    htmlspecialchars() in Javascript

    it seems that we need to write our own version of PHP's htmlspecialchars() if we want to do it in javascript huh?

    let's say if we want to do things like

    document.getElementById("divCode").innerHTML = "if (a < 10) { ... }";

    or

    document.getElementById("divCode").innerHTML = "use <span> if you want to ... Use &copy; if you want to...";

    then we will need to change the "<" into &lt; (and so forth for the "&" etc) so it will be handy if there is a built-in function that will do that. Looks like prototype.js doesn't have that if i do a search on google using

    htmlspecialchars site: prototypejs.org

    Thanks very much!
    Last edited by winterheat; Sep 4, 2008 at 19:32.

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Using the standard DOM methods seems to work fine.

    Code javascript:
    var text = document.createTextNode('use <span> if you want to ... Use &copy; if you want to...');
    document.getElementById('divCode').appendChild(text);

    If instead of adding to the container, you want the contents to be replaced, remove the contents first before adding to it.

    Code javascript:
    var el = document.getElementById('divCode');
    var text = document.createTextNode('use <span> if you want to ... Use &copy; if you want to...');
    while (el.firstChild) {
        el.removeChild(el.firstChild);
    }
    el.appendChild(text);
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    There isn't anything built iin, but you can easily define one:
    Code:
    escapeHTML = function(s) {
      return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    };
    escapeHTML("<span> & stuff");


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •