Regex capitalize first letter every word, also after a special character like a dash

Simmer picture Simmer · Jun 6, 2011 · Viewed 84.5k times · Source

I use this #(\s|^)([a-z0-9-_]+)#i for capitalize every first letter every word, i want it also to capitalize the letter if it's after a special mark like a dash(-)

Now it shows:

This Is A Test For-stackoverflow

And i want this:

This Is A Test For-Stackoverflow

Any suggestions/samples for me?

I'am not a pro, so try to keep it simple for me to understand.

Answer

NotNedLudd picture NotNedLudd · Apr 25, 2015

+1 for word boundaries, and here is a comparable Javascript solution. This accounts for possessives, as well:

var re = /(\b[a-z](?!\s))/g;
var s = "fort collins, croton-on-hudson, harper's ferry, coeur d'alene, o'fallon"; 
s = s.replace(re, function(x){return x.toUpperCase();});
console.log(s); // "Fort Collins, Croton-On-Hudson, Harper's Ferry, Coeur D'Alene, O'Fallon"