How can i turn Turkish chars to ascii?

Viewed 51

How can I turn Turkish chars to ASCII? (like ş to s)

I tried replace but it didn't do anything. Here is my code:

$posta = $posta.ToLower()
$posta = $posta -replace "ü","u" 
$posta = $posta -replace "ı","i"
$posta = $posta -replace "ö","o"
$posta = $posta -replace "ç","c"
$posta = $posta -replace "ş","s"
$posta = $posta -replace "ğ","g"
$posta = $posta.trim()
write-host $posta

if $posta was eylül it returns eylül

2 Answers

All credits to this answer combined with the comment in the same answer which shows the appropriate way to do it by filtering for characters which are not NonSpacingMark followed by replacing ı with i. The answer is in hence sharing how it can be done in .

$posta = 'üıöçşğ'
$posta = [string]::Join('',
    $posta.Normalize([Text.NormalizationForm]::FormD).ToCharArray().
    Where{ [char]::GetUnicodeCategory($_) -ne [Globalization.UnicodeCategory]::NonSpacingMark }
).Replace("ı", "i")

To complement Santiago Squarzon's helpful answer with a PowerShell (Core) 7+ alternative, which builds on the guidance in this helpful answer, explaining that there is a fixed set of 12 characters in the Turkish alphabet that have equivalent ASCII characters:

  • Note: Santiago's answer uses an approach that generally removes the accents (diacritics) from letters, and then adds Turkish-specific ı handling. The solution below is specific to the Turkish alphabet (and is case-sensitive; it could easily be adapted to be case-insensitive / all-lowercase).
# PS 7+

$turkish = 'ıİöÖçÇüÜğĞşŞ' # Turkish chars. with ASCII equivalents...
$ascii   = 'iIoOcCuUgGsS' # ...and their ASCII equivalents.

# Replace those Turkish chars. that have ASCII equivalents with their equivalents.
# ->  'A_iIoOcCuUgGsS_Z'
'A_ıİöÖçÇüÜğĞşŞ_Z' -replace ('[' + $turkish + ']'),
                            { $ascii[$turkish.IndexOf($_.Value)] }

This solution relies on a PowerShell (Core) 7+ feature of the regex-based -replace operator, namely the option to pass a script block ({ ... }) as the replacement operand, which enables determining the replacement value algorithmically, based on each reported match ($_.Value).

Related