I have a sentence with a colon in the middle, and want to capitalize the first word after the colon, I would like to know how to replace the matching letter with its' upper case using regexp in javascript, however xx.replace(/(:\s\w)/, '$1'.toUpperCase())
doesn't work, it returns Lactobacillus strains: a BIOPEP-UWM database-based analysis
. Expect Lactobacillus strains: A BIOPEP-UWM database-based analysis
.
MWE:
var xx = 'Lactobacillus strains: a BIOPEP-UWM database-based analysis';
xx.replace(/(:\s\w)/, '$1'.toUpperCase());
Any suggestion is appreciated.
CodePudding user response:
All you need to do is use a callback function as the second argument instead of '$1'
var xx = 'Lactobacillus strains: a BIOPEP-UWM database-based analysis';
console.log(xx.replace(/:\s\w/, fullMatch => fullMatch.toUpperCase()));
What you were doing was capitalizing the literal value '$1'
, which is the same, so it was just passing '$1'
into the replace function
CodePudding user response:
The following regex ... /(?<=:\s*)\p{Ll}/gu
... matches exactly just any lowercase letter which follows a colon and an optional whitespace (sequence). It does so by using the unicode property escape for a lowercase letter ... \p{Ll}
... and by utilizing a positive lookbehind.
const sampleText =
`Lactobacillus strains: a BIOPEP-UWM database-based analysis
Lactobacillus strains :another BIOPEP-UWM database-based analysis
Lactobacillus strains : a BIOPEP-UWM database-based analysis
Lactobacillus strains:another BIOPEP-UWM database-based analysis
Lactobacillus strains:Another BIOPEP-UWM database-based analysis`;
// see ... [https://regex101.com/r/dXfa2j/1]
const regXLowerCaseAfterColon = /(?<=:\s*)\p{Ll}/gu;
console.log(
sampleText
.replace(regXLowerCaseAfterColon, match => match.toUpperCase())
);
.as-console-wrapper { min-height: 100%!important; top: 0; }