Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to capitalize the next char after " Mc"

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.

like image 695
kasdega Avatar asked Aug 22 '11 20:08

kasdega


2 Answers

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"
like image 147
maerics Avatar answered Sep 29 '22 13:09

maerics


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.

like image 43
jfriend00 Avatar answered Sep 29 '22 15:09

jfriend00