Home > Enterprise >  Capitalize all letters of matching regex result - null, [...], and [...,...]
Capitalize all letters of matching regex result - null, [...], and [...,...]

Time:12-15

I've got a regex that returns all instances of two letter words. The results come back as either null or an array of unknown amount of items.

const regex_all_two_letter_words = /(\b\w{2}\b)/g;
var regexCapitalize = /[A-Z] /g;

// inputs
const testString = [
    "j handcock",
    "je handcock",
    "jim handcock",
    "jim j handcock",
    "jim je handcock,",
    "jim jer handcock",
    "j handcock",
    "j. e, handcock",
    "j. er handcock jr",
    "jim js handcock sr",
    "jim handcock nn",
];

testString.forEach((str) => {
    var test = str.match(regex_all_two_letter_words);
    console.log(test);
});

Returns

null
[ 'je' ]
null
null
[ 'je' ]
null
null
null
[ 'er', 'jr' ]
[ 'js', 'sr' ]
[ 'nn' ]

I'm trying to capitalize both letters and replace the lowercase variants with the uppercase.

My best attempt so far:

    /// Inside the forEach function
    var finalStr = function (test) {
        if (test !== null) {
            var text = test.replace(regexCapitalize);
            return text;
        }
        return text;
    };

(Returns a bunch of functions)

Thanks

CodePudding user response:

const testStrings = [
    "j handcock",
    "je handcock",
    "jim handcock",
    "jim j handcock",
    "jim je handcock,",
    "jim jer handcock",
    "j handcock",
    "j. e, handcock",
    "j. er handcock jr",
    "jim js handcock sr",
    "jim handcock nn",
]
console.log(
  testStrings.map(s=>s.split(' ')
    .map(i=>i.replaceAll(/[^a-z]/ig,'').length===2?i.toUpperCase():i)
    .join(' '))
)

  • Related