How can I use a single regular expression to replace all words town
with village
preserving the case of the first letter of each match?
Example input:
Towns are small cities. I live in a town.
Desired output:
Villages are small cities. I live in a village.
How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group. For more information about numbered capturing groups, see Grouping Constructs.
Regular expressions are used with the RegExp methods test() and exec() and with the String methods match() , replace() , search() , and split() . Executes a search for a match in a string.
$_ = "Towns are small cities. I live in a town.\n";
s{ \b (?: (T)|(t) ) own }
{ $1 ? "Village" : "village" }xge;
print;
# prints: Villages are small cities. I live in a village.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With