更新:2007 年 11 月
确定 String 对象的开头部分是否与指定的字符串匹配。
var hasPrefix = myString.startsWith(prefix);
参数
- prefix
要与 String 对象的开头部分进行匹配的字符串。
返回值
如果 String 对象的开头部分与 prefix 匹配,则该值为 true;否则为 false。
备注
使用 startsWith 函数可确定 String 对象的开头部分是否与指定的字符串匹配。startsWith 函数区分大小写。
示例
下面的示例演示如何使用 startsWith 函数来确定字符串的开头部分是否与指定的字符串匹配。该代码调用 String.trimStart 函数,以免验证字符串开头部分中的非空格字符。接下来,代码调用 String.toLowerCase 函数,这样验证时就无须区分大小写。最后,代码调用 startsWith 函数来测试字符串的开头部分是否匹配。
<!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>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>