我收到此错误:无法在 String.toJadenCase 调用未定义的方法“替换”
I get this error: Cannot call method 'replace' of undefined at String.toJadenCase
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();});
}
我将正则表达式更改为使用单词分隔符,并且是全局的。
相关文章:
- 得到"TypeError:无法读取属性'filename'未定义的“;调用“npm start
- AngularJS和promise值在调用本地函数时的效果-未定义
- 为什么这个函数调用会破坏程序并导致未定义的变量
- React路由器错误-'无法调用方法'getRouteAtDepth'的未定义'
- 在不兼容的接收器上调用的方法Set.prototype.add未定义
- PhoneGap无法调用未定义的方法loadurl
- TinyMCE验证给出错误:无法调用方法'getContent'的未定义
- setInterval调用具有未定义参数的函数
- 返回List<字符串>Jquery中的from JSON调用具有未定义的长度
- REST调用总是返回未定义的(Node.JS)
- 如何处理 getJSON 调用上的“未捕获类型错误:无法设置未定义的属性'prop'”
- Javascript/jQuery - “无法调用未定义的方法'push'”,而它是定义的
- 对象不支持在调用 indexOf 定义的数组时 IE8 中未定义的此属性或方法
- 未捕获的类型错误:无法调用方法'至小写'的未定义
- *简单*解析云代码查询失败”;TypeError:无法调用方法'获取'未定义的“检索该信息”;
- 无法调用方法'应用'关于为jquery谷歌地图插件设置方向的未定义
- moment:Array.prototype.some在null或未定义时被调用
- 调用javascript函数时未定义
- 未捕获的类型错误:无法调用方法'每个'的未定义
- Alt flux action:_this.actions未定义,即使调用了this.generateActions