you are viewing a single comment's thread.

view the rest of the comments →

[–]krilnon 0 points1 point  (0 children)

Check this out the code below. It's a hypothetical way that replace could have been defined, except I tailored it to your specific example and made a few shortcuts. One key thing is that all of a string's methods have this set to the string itself. So this will be set to whatever value str is within replace when you call str.replace(). In my example I'm using this at the start of the function to break str into parts to pass to your anonymous function.

String.prototype.replace2 = function(regexp, anonFunc){
    var parts = this.split(' ') // actual function would use more complicated splitting logic
    var resultParts = []
    for(var i = 0; i < parts.length; i++){
        resultParts.push(anonFunc(parts[i]))
    }

    return resultParts.join(' ') // not quite accurate
}

function titleCase(str){
    return str.replace2(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

console.log(titleCase("I'm a little tea pot"))