PowerShell: Replace Only First Occurrence of Word in String


Often you may want to use PowerShell to only replace the first occurrence of a particular word in a string.

You can use the following syntax to do so:

[regex]$word = "team"
$word.replace($my_string, "franchise", 1)

This particular example replaces only the first occurrence of the word “team” in the string variable named $my_string.

By specifying 1 as the last argument in the replace() command we are able to tell PowerShell to only replace the first occurrence.

If we used a 2 instead, then it would replace only the first two occurrences, and so on.

The following example shows how to use this syntax in practice.

Example: Replace Only First Occurrence of Word in String in PowerShell

Suppose we create a string variable named $my_string in PowerShell that contains the following text:

  • “They are a great team and the best team”

Suppose that we would like to replace only the first occurrence of the word “team” with the word “franchise” instead.

We can use the following syntax to do so:

$my_string = "They are a great team and the best team"

[regex]$word = "team"
$word.replace($my_string, "franchise", 1)

The following screenshot shows how to use this syntax in practice:

PowerShell replace first occurrence of word in string

Notice that this produces the following string:

  • “They are a great franchise and the best team”

Notice that only the first occurrence of the word “team” has been replaced while all other occurrences have been left unchanged.

Feel free to use similar syntax to replace only the first occurrence of any particular word in your own string.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Text in String
PowerShell: How to Get String Length of Variable
PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Check if String Exists in List of Strings

Leave a Reply