简体   繁体   中英

Processing different matches in a RegExp

I want to construct a RegExp that matches either the first letter of the first word, or the first letter of non-first words, but I want to be able to distinguish between these two kinds matches so I can process non-first-word matches differently.

For example I want to always capitalise the first word and all other words apart from instances of "bam" that are not the first word.

How can I do this?

function titleCase(title) {
    return title.replace(/\b(.)/g, (str, p1) => {         
         return p1.toUpperCase();
    });
}

titleCase('foo bar bam'); // Foo Bar Bam - but I want Foo Bar bam

You can put multiple regex pieces together like /(option 1)|(option 2)/g

Then your callback will receive either of:

callback(match, option1, undefined, offset, subject) // left side matched
callback(match, undefined, option2, offset, subject) // right side matched

Using this, your callback can look like:

(str, p1, p2) => {
    if( p1) ...
    else if( p2) ...
}

Here is an implementation of titleCase which will capitalize the first letter of every word-like element in the string.

function titleCase(title) {
  return title.replace(/\b(\w)(.*?)\b/g, (match, g1, g2) => `${g1.toUpperCase()}${g2}`)
}
  1. In this example, /\\b(\\w)(.*?)\\b/g will match a word boundary ( \\b ) followed by a word character ( \\w ). We capture the first letter using the grouping (\\w) , and is used as g1 in the replace function.
  2. Then we capture the remaining portion of the word using the group (.*?) , which is referenced using g2 in the replacer.
  3. Finally, a template string is used to capitalize the first letter group and concatenate the result with the remaining match of the word.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM