Reputation: 3665
So I am going through this book and copied the code word for word to be hands on with it and I am getting "Object doesn't support this property or method".
var text = '<html><body bgcolor=blue><p>' + '<This is <b>BOLD<\/b>!<\/p><\/body><\/html>';
var tags = /[^<>]+|<(\/?)([A-Za-z]+)([^<>]*)>/g;
var a,i;
String.method('entityify', function () {
var character = {
'<': '<',
'>': '>',
'&': '&',
'"': '"'
};
return function() {
return this.replace( /[<>&"]/g , function(c) {
return character[c];
});
};
}());
while((a = tags.exec(text))) {
for (i = 0; i < a.length; i += 1) {
document.writeln(('// [' + i + '] ' + a[i]).entityify());
}
document.writeln();
}
//Output [0] <html>
//Output [1]
//Output [2] html
//Output [3]
//and so on through the loop.
I can't seem to make their example work.
**Edit - I found and added the function but still not quite working.
Upvotes: 0
Views: 801
Reputation: 156434
The problem is that there is no String.method(...)
function. If you're trying to add a new function to the String type then try this:
String.prototype.entityify = (function () {
var character = {
'<':'<', '>':'>', '&':'&', '"':'"'
};
return function() {
return this.replace( /[<>&"]/g , function(c) {
return character[c];
});
};
})();
'<foo & bar>'.entityify(); // => "<foo & bar>"
Although, if you plan to make this part of a library then you should not assign to the String.prototype
directly, instead use Object.defineProperty(...)
as illustrated here.
Upvotes: 1