Search code examples
stringvbscriptstripwsh

VbScript to strip space of string?


Say I have a string that = Grilled Cheese

How would I echo the string without the space between Grilled Cheese with out changing the string?

Also if I had a string that variables but will always have a space, like a full name. I can show the first letter of the string:

WScript.Echo Left(strUserName, 1) will echo for example G

but how could I show the name after the space (= Cheese). Keep in mind the name after the space may change like "Cheesy" for example

WScript.Echo Mid(strUserName,null) does not work

Thanks!


Solution

  • The Replace function can be used to remove characters from a string. If you just echo the return value without assigning it back to the variable, the original string will remain unchanged:

    >>> str = "Grilled Cheese"
    >>> WScript.Echo Replace(str, " ", "")
    GrilledCheese
    >>> WScript.Echo str
    Grilled Cheese

    Another option would be the Split and Join functions:

    >>> str = "Grilled Cheese"
    >>> WScript.Echo Join(Split(str, " "), "")
    GrilledCheese
    >>> WScript.Echo str
    Grilled Cheese

    Split will also allow you to echo just particular tokens from the original string:

    >>> str = "Grilled Cheese"
    >>> WScript.Echo Split(str, " ")(1)
    Cheese