Replacing only the first occurrence of a word in a string

One way to replace n times:

$test = "My name is Bob, her name is Sara."
[regex]$pattern = "name"
$pattern.replace($test, "baby", 1) 

> My baby is Bob, her name is Sara

Leave a Comment