开发者

Taking a String and Capitalizing the first character - Why is this killing the browser

given a string like bobby, I want to the function to return Bobby.

I ha开发者_Python百科ve the following:

// Capitalizes the first letter.
function toTitleCase(str) {
    return str.replace(/(?:^|\s)\w/g, function(match) {
        return match.toUpperCase();
    });
}

For some reason this is killing the browser, any ideas why? Did I missing something with the REGEX that could be causing memory issues? thanks


Why use regex for something like this?

var s = "my string";
s = s.substring(0, 1).toUpperCase() + s.substring(1);
console.log(s);

Regex is quite a bit more expensive to use than native string functions and as such should only be used when nothing else will solve your particular problem.

Edit

On another note, I'm not sure why it's causing your browser to bail, I have no issues running what you have in either FF or Chrome.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜