Brad Brad - 1 month ago 8
Javascript Question

First letter capitalisation function also capitalising after apostrophe

I have a function which capitalises the first letter of each word:

function format(str){
str = str.replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
return str;
}


It is also capitalising after an apostrophe:

console.log(format("mark")); //Mark (correct)
console.log(format("mark o'loughlan")); //Mark O'Loughlan (correct)
console.log(format("mark's audi")); //Mark'S Audi (incorect)


Ideally, I'd like it to capitalise after an apostrophe if it's a name (example 2), but not for 's (example 3). How can I fix this? Fiddle here

Edit: I don't think this is a duplicate of this question, as I'm specifically asking about not capitalising 's but after other apostrophe's is ok.

Answer

Unfortunately, Javascript regex does not have a lookbehind syntax to do it all in one regex, however, you can do it in two steps. Uppercase as you are now, but then lowercase the 'S after the fact.

var strings = [
    "mark", 
    "mark o'loughlan",
    "mark's audi"
]

var returnValue = "";
function format(str){
    str = str.replace(/\b[a-z]/g, function(letter) { return letter.toUpperCase(); });
    str = str.replace(/'(S)/g, function(letter) { return letter.toLowerCase(); });
    return str;
}

strings.forEach(function(string){
    console.log(format(string));
});