Home > Enterprise >  A question about a regex expression from Jaden Casing Strings with JS (a kata from Codewars)
A question about a regex expression from Jaden Casing Strings with JS (a kata from Codewars)

Time:02-21

Been stupid around lately. Recently I had no idea about how to capture every first letter in the string. I googled. As I understood, \b matches every first letter plus space before them. So, I wrote a regex: (\b)[^'] and it works perfectly with strings except for the part with the short form like 'aren't' or 'doesn't'. My reg captures this 't' that shouldn't be captured. Could you tell me what is wrong with my reg?

Thanks ahead. I am a beginner, so I am sorry if I have a dumb code xd

Code:

String.prototype.toJadenCase = function () {
    return this.replace(/(\b)[^']/g, function(x) { 
        return x.toUpperCase();
    });
}
// output: How Can Mirrors Be Real If Our Eyes Aren'T Real
console.log("How can mirrors be real if our eyes aren't real".toJadenCase());
// output: Most Trees Are Blue
console.log('most Trees Are Blue'.toJadenCase());
// output: Why This Doesn'T Work
console.log("why This Doesn't work".toJadenCase());

CodePudding user response:

As I understood, \b matches every first letter plus space before them.

This is not really what it does. It doesn't match a character. It matches a position without matching a single character. The position is matched when exactly one character among the character before and character after that position is alphanumeric (or underscore).

So in this particular task you have to avoid a match with 't, since the \b will match the position between these two characters. So you could use a look-behind check, to check that the character before that position is not a '. You should also check that the character after that position is the one that is the letter, as otherwise you'll also match the position just after every word.

So use: /(?<!')\b[a-z]/g

The (?<!') part asserts that the preceding character is not a quote

  • Related