String.startsWith Function

Determines whether the start of a String object matches a specified string.

var hasPrefix = myString.startsWith(prefix);

Arguments

  • prefix
    The string to match with the start of the String object.

Return Value

true if the start of the String object matches prefix; otherwise, false.

Remarks

Use the startsWith function to determine whether the start of a String object matches a specified string. The startsWith function is case sensitive.

Example

The following example shows how to use the startsWith function to determine whether the start of a string matches a specified string. The code excludes non-white-space characters at the start of the string from the validation by invoking the String.trimStart function. Next it calls the String.toLowerCase function so that case sensitivity is also excluded from the validation. Finally, it calls the startsWith function invoked to test the start of the string for a match.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Sample</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager runat="server" ID="ScriptManager1">
        </asp:ScriptManager>

        <script type="text/javascript">
            // Determines if a string has a specific prefix as 
            // the first non white-space characters in a string.
            function verifyString(myString, prefix) 
            {
                // Remove any white space at the left of the string.
                myString = myString.trimStart();

                // Set to lower case.
                myString = myString.toLowerCase();

                // Determine if the string starts with the specified prefix.
                var hasPrefix = myString.startsWith(prefix.toString());
                if (hasPrefix === true)
                {
                    alert("The string \"" + myString + "\" starts with \"" + prefix + "\""); 
                }
                else
                {
                   alert("The string \"" + myString + " does not start with \"" + prefix + "\""); 
                }
             }

            // Displays: The string "green_blue_red" starts with "green"
            verifyString("  GREEN_BLUE_RED  ", "green");

        </script>
    </form>
</body>
</html>

See Also

Reference

String.endsWith Function

Other Resources

Language Reference