Removing quotes from a string

PowerShell:
Removing quotes from a string

How to:

You can use the -replace operator to strip quotes from a string. Here’s how:

# Replace single quotes
$stringWithSingleQuotes = "'Hello, World!'"
$cleanString = $stringWithSingleQuotes -replace "'", ""
Write-Output $cleanString  # Output: Hello, World!

# Replace double quotes
$stringWithDoubleQuotes = '"Hello, World!"'
$cleanString = $stringWithDoubleQuotes -replace '"', ""
Write-Output $cleanString  # Output: Hello, World!

For both types:

$stringWithQuotes = '"Hi there," she said.'
$cleanString = $stringWithQuotes -replace "[\"']", ""  # Note the use of regex character class
Write-Output $cleanString  # Output: Hi there, she said.

Sample output from the console will look something like this:

Hello, World!
Hello, World!
Hi there, she said.

Deep Dive

Back in the day, before PowerShell was a twinkle in Microsoft’s eye, text processing in Windows was often the domain of batch scripts that had limited capabilities. PowerShell’s introduction brought with it powerful string manipulation features that made scripting much more robust.

Alternatives to -replace exist, such as using the .Trim() method to remove quotes only at the start and end of a string, but they don’t offer the same control or regex support.

# Using .Trim() for quotes at the start and end
$stringWithQuotes = '"Hello, World!"'
$cleanString = $stringWithQuotes.Trim('"')
Write-Output $cleanString  # Output: Hello, World!

Do note, -replace uses regex behind the scenes, so when you’re working with it, keep in mind special characters need to be escaped if you’re targeting them. If you need more granular control over the quotes removal, diving into regex with -replace is the way to go, giving you immense flexibility.

See Also