我收到此错误:无法在 String.toJadenCase 调用未定义的方法“替换”

I get this error: Cannot call method 'replace' of undefined at String.toJadenCase

本文关键字:未定义 调用 toJadenCase 方法 替换 String 错误      更新时间:2023-09-26
String.prototype.toJadenCase = function (str) {
  //...
 var capitalize = str; 
 return capitalize.replace(/^[a-zA-Z]*$/, function(txt){
     return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

当我传递字符串"如果我们的眼睛不是真实的,镜子怎么可能是真实的"作为参数时,我得到了错误。它应该返回大写的每个单词,例如:"如果我们的眼睛不是真实的,镜子怎么可能是真实的"。

我是JS和编程的新手,所以这可能是微不足道的。

toJadenCase 方法在String的上下文中运行,因此请使用 this 关键字检索文本。您还需要稍微摆弄一下正则表达式:

String.prototype.toJadenCase = function () {
        return this.replace(/'w'S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
var copy = "How can mirrors be real if our eyes aren't real";
alert(copy.toJadenCase());

请注意,这会优雅地处理您的逗号。

由于您的函数需要一个参数,因此调用它的方式是:

myStr.toJadenCase(myStr);

这不是你想要的。

但是,如果您改用this,它将起作用:

return this.replace(/^[a-zA-Z]*$/, function(txt){
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});

(这消除了错误,但您的案例更改代码未按预期工作)

无需参数即可使用this。正则表达式'b匹配单词边界处的字符。

String.prototype.toJadenCase = function () {
    return this.replace(/'b./g, function(m){ 
        return m.toUpperCase();    
    });
}

正则表达式不处理特殊情况,如aren't。您必须匹配一个空格,后跟一个字符。为此,您可以改为使用

String.prototype.toJadenCase = function () {
    return this.replace(/'s./g, function(m){ 
        return m.toUpperCase();    
    });
}

或者更具体地说,您可以使用 /'s[a-zA-Z]/g .

您可以在此处看到正则表达式的运行情况。

用法

str = "How can mirrors be real if our eyes aren't real";
console.log(str.toJadenCase());
你想

让它使用this,而且,你的正则表达式是错误的。

function () {
 return this.replace(/'b[a-zA-Z]*'b/g, function(txt){
     return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

我将正则表达式更改为使用单词分隔符,并且是全局的。