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}`)
}
/\\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. (.*?)
, which is referenced using g2
in the replacer.
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.