Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to execute Doug Crockford's deentityify example in jsfiddle

Tags:

javascript

I am trying to execute that really nice deentityify example in Douglas Crockfords J-TBP book using jsfiddle

String.method('deentityify', function() {
    // The entity table. It maps entity names to
    // characters.
    var entity = {
        quot: '"',
        lt: '<',
        gt: '>'
    };
    // Return the deentityify method.
    return function() {
        // This is the deentityify method. It calls the string
        // replace method, looking for substrings that start
        // with '&' and end with ';'. If the characters in
        // between are in the entity table, then replace the
        // entity with the character from the table. It uses
        // a regular expression (Chapter 7).
        return this.replace(/&([^&;]+);/g, function(a, b) {
            var r = entity[b];
            return typeof r === 'string' ? r : a;
        });
    };
}());

document.writeln('&lt;&quot;&gt;'.deentityify()); // <">          
  • see http://jsfiddle.net/cspeter8/7Pjzs/2/ - and it does not work! I would expect the results pane to display '<">' but nothing shows up. Would someone like to solve the mystery?
like image 243
cspeter8 Avatar asked Feb 19 '23 12:02

cspeter8


1 Answers

This code-snippet depends on a bit of sugar, namely the method method, that you have to define beforehand. (It's described early on in the book.) An online copy and explanation of it are in the "Sugar" section of Crockford's article "Classical Inheritance in JavaScript". It looks like this:

Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};

A corrected version of your Fiddle, incorporating the above, is at http://jsfiddle.net/W9Ncd/.

like image 196
ruakh Avatar answered Feb 21 '23 01:02

ruakh