My goal is to know how this kind of text $var1 = "my-name-is"
convert to camelCase"myNameIs"
.
And this type $var2 = "my_Name_is"
convert to PascalCase"MyNameIs"
Have no idea how to do it
My goal is to know how this kind of text $var1 = "my-name-is"
convert to camelCase"myNameIs"
.
And this type $var2 = "my_Name_is"
convert to PascalCase"MyNameIs"
Have no idea how to do it
You might use the .NET TextInfo.ToTitleCase(String)
method for this.
For PascalCase this is quiet straight forward:
$Text = $Var1 -Replace '[^0-9A-Z]', ' '
(Get-Culture).TextInfo.ToTitleCase($Text) -Replace ' '
For camelCase there is a little more at stake:
$First, $Rest = $Var2 -Replace '[^0-9A-Z]', ' ' -Split ' ',2
$First.Tolower() + (Get-Culture).TextInfo.ToTitleCase($Rest) -Replace ' '
'my_Name_is' -Replace '[^0-9A-Z]', ' '
Replaces any character that isn't Alphanumeric with a space (result: my Name is
).
(Note that PowerShell is case insensitive by default)
'my Name is' -Split ' ',2
Splits the word ('my'
) from the rest ('Name is'
).
$First, $Rest = 'my', 'Name is'
Stores the first word in $First
and the rest in $Rest
.
$First.Tolower() + (Get-Culture).TextInfo.ToTitleCase($Rest)
Puts the first word in lowercase and the rest in title case (result: myName Is
)
'myName Is' -Replace ' '
Removes any spaces (result: myNameIs
).
PowerShell (Core) 7+ solution, taking advantage of the ability to use script blocks ({ ... }
) to perform dynamic replacements via the regex-based -replace
operator:
# camelCase (separator char. in input string is "-")
PS> "my-name-is" -replace '-(\p{L})', { $_.Groups[1].Value.ToUpper() }
myNameIs
# PascalCase (separator char. in input string is "_")
PS> "my_Name_is" -replace '(?:^|_)(\p{L})', { $_.Groups[1].Value.ToUpper() }
MyNameIs
Windows PowerShell solution:
Direct use of the underlying .NET APIs is required, because use of script blocks as -replace
's replacement operand aren't supported in this edition.
# camelCase
PS> [regex]::Replace("my-name-is", '(?i)-(\p{L})', { $args[0].Groups[1].Value.ToUpper() })
myNameIs
# PascalCase
PS> [regex]::Replace("my_Name_is", '(?i)(?:^|_)(\p{L})', { $args[0].Groups[1].Value.ToUpper() })
MyNameIs
This function will help you out!
$var1 = "my-name-is"
function ToCamelCase($str){
$bits = @()
foreach($token in $str.Split('-')) {
$newBit = $token[0].ToString().ToUpper(), $token.TrimStart($token[0]) -join ''
$bits +=$newBIt
}
$bits -join ''
}
PS> ToCamelCase $VAR1
MyNameIs
To convert dashed string to Camel Case you can use one-liner:
$t.Substring(0,1).ToLower() + ((Get-Culture).TextInfo.ToTitleCase(($t.ToLower() -replace "-", " ")) -replace " ", "").Substring(1)