String.endsWith 函数

更新:2007 年 11 月

确定 String 对象的末尾是否与指定的字符串匹配。

var hasSuffixVar = myString.endsWith(suffix);

参数

  • suffix
    要与 String 对象的末尾进行匹配的字符串。

返回值

如果 String 对象的末尾与 suffix 匹配,则为 true;否则为 false。

备注

使用 endsWith 函数可确定 String 对象的末尾是否与指定的字符串匹配。endsWith 函数区分大小写。

示例

下面的示例演示如何使用 endsWith 函数来确定某个字符串的末尾是否与指定的字符串匹配。其中的代码通过调用 String.trimEnd 函数来避免验证字符串末尾的非空白字符。接下来,代码调用 String.toLowerCase 函数,这样验证时就无须区分大小写。最后,代码调用 endsWith 函数来测试字符串的末尾是否匹配。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Untitled Page</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 specified suffix as 
            // the last non white-space characters regardless of case.
            function verifyStringSuffix(myString, suffix) 
            {
                // Remove any trailing white spaces.
                myString = myString.trimEnd();

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

                // Determine if the string ends with the specified suffix.
                var isTxt = myString.endsWith(suffix.toString());

                if (isTxt === true)
                {
                    alert("The string \"" + myString + "\" ends with \"" + suffix + "\""); 
                }
                else
                {
                   alert("The string \"" + myString + "\" does not end with \"" + suffix + "\""); 
                }
            }

            verifyStringSuffix("some_file.TXT  ", ".txt");

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


请参见

参考

String.startsWith 函数

String 对象

其他资源

语言参考