PowerShell: How to Remove HTML Tags from a String


Often you may want to use PowerShell to remove HTML tags from a string.

You can use the following basic syntax to do so:

$my_string -replace '<[^>]+>',''

This particular example removes all HTML tags from the string stored in the variable named $my_string.

Note that this method uses the -replace operator to replace all occurrences of patterns that start with the <  symbol and are followed by any number of characters not equal to > and are then followed by the > symbol.

Note that we specify no replacement pattern to use, which allows us to simply remove all HTML tags from the string.

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

Example: How to Remove HTML Tags from a String in PowerShell

Suppose that we have a string variable named $my_string in PowerShell that contains the following HTML content:

$my_string = '<p>We will have a <span id="new">great day</span></p>'

Notice that this string contains two sets of HTML tags:

  • <p> and </p>
  • <span> and </span>

We can use the following syntax to remove all of these HTML tags from the string:

$my_string -replace '<[^>]+>',''

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

PowerShell replace HTML tags

The output contains the following new string:

  • We will have a great day

This string is equivalent to the original string with all HTML tags removed.

Note: You can find the complete documentation for the -replace operator in PowerShell here.

Related Tutorials

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

PowerShell: How to Sort a Table with Format-Table
PowerShell: How to Sort by Specific Column
PowerShell: How to Use Sort-Object with Multiple Properties

Leave a Reply