Given a string like Marty Mcfly
is there a regex or other one line solution to capitalize the 'f' so I get Marty McFly
?
I can always count on the space between first and last and the first letter of the last name (i.e. the M) will always be caps.
I'm pretty open to just about any javascript, jquery, regex solution, I just need it to be short and sweet.
I've got a method that takes the string apart using indexOf and substring but I'm hoping theres a regex or something similar.
You can take advantage of the form of String.replace
which takes a function as its second argument:
function fixMarty(s) {
return (""+s).replace(/Mc(.)/g, function(m, m1) {
return 'Mc' + m1.toUpperCase();
});
}
fixMarty('Marty Mcfly'); // => "Marty McFly"
fixMarty("Mcdonald's"); // => "McDonald's"
This is a perfect case for using a callback with .replace()
.
function fixMc(str) {
return(str.replace(/\bMc(\w)/, function(match, p1) {
return(match.slice(0, -1) + p1.toUpperCase());
}));
}
Here's a jsFiddle http://jsfiddle.net/jfriend00/Qbf8R/ where you can see it in action on a several different test cases.
By way of explanation for the how the callback works, the parameter match
is the whole regex match, the parameter p1
is what the first parenthesized group matched and the callback returns what you want to replace the whole regex match with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With