【问题标题】:I get this error: Cannot call method 'replace' of undefined at String.toJadenCase我收到此错误:Cannot call method 'replace' of undefined at String.toJadenCase
【发布时间】:2015-01-25 12:20:21
【问题描述】:
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 和一般编程的新手,所以这可能是微不足道的。

【问题讨论】:

    标签: javascript regex string uppercase


    【解决方案1】:

    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());

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

    【讨论】:

      【解决方案2】:

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

      myStr.toJadenCase(myStr);
      

      这不是你想要的。

      但是,如果你改用this,它会起作用:

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

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

      【讨论】:

        【解决方案3】:

        您可以使用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

        您可以看到正在运行的正则表达式here

        用法

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

        【讨论】:

          【解决方案4】:

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

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-09-20
            • 2013-01-15
            • 2013-05-02
            • 2022-01-16
            • 1970-01-01
            • 2019-04-05
            • 1970-01-01
            • 2023-03-09
            相关资源
            最近更新 更多