开发者

Javascript to capitalize the next char after " Mc"

开发者 https://www.devze.com 2023-03-29 17:58 出处:网络
Given a string like Marty Mcfly is there a regex or other one line solution to capitalize the \'f\' so I get Marty McFly?

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 th开发者_高级运维at 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.


var text = 'Marty Mcfly';
text = text.replace(/Mc[a-z]/, function (k)
    {
      return 'Mc' + k[2].toUpperCase();
    }
  );


Use a combination of RegEx's exec method and String's replace method:

var name = 'Marty Mcfly',
    pattern = /\bmc([a-z])/gi,
    match = pattern.exec(name);

if (match) {
    alert(name.replace(pattern, 'Mc' + match[1].toUpperCase()));
}

Here's a version that works with "Mac":

var name = 'Connor Macleod',
    pattern = /\b(mc|mac)([a-z])/gi,
    match = pattern.exec(name);

if (match) {
    alert(name.replace(pattern, match[1] + match[2].toUpperCase()));
}


Here's the best I can do:

'Marty Mcfly'.replace(/ mc([a-z])/i, function (str, $1) {return  " Mc" + $1.toUpperCase()})
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号