使用正则表达式时出现 Javascript 错误 - 对象不支持此属性或方法

Javascript Error when using regexp - Object doesn't support this property or method

本文关键字:不支持 对象 属性 方法 错误 正则表达式 Javascript      更新时间:2023-09-26

所以我正在阅读这本书并逐字复制代码以动手使用它,我得到"对象不支持此属性或方法"。

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 = {
    '<': '&lt;',
    '>': '&gt;',
    '&': '&amp;',
    '"': '&quot;'
};
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.

我似乎无法让他们的例子起作用。

**编辑 - 我找到并添加了该功能,但仍然无法正常工作。

问题是没有String.method(...)函数。 如果您尝试向字符串类型添加新函数,请尝试以下操作:

String.prototype.entityify = (function () {
  var character = {
    '<':'&lt;',  '>':'&gt;',  '&':'&amp;',  '"':'&quot;'
  };
  return function() {
    return this.replace( /[<>&"]/g , function(c) {
      return character[c];
    });
  };
})();
'<foo & bar>'.entityify(); // => "&lt;foo &amp; bar&gt;"

虽然,如果您打算将此部分作为库的一部分,则不应直接分配给String.prototype,而应使用此处所示的Object.defineProperty(...)