我有一个关于使用字符串对象的适当方法来搜索字符串中的字符串的学校作业。大部分页面都是为我们提供的。我们的工作是创建将执行搜索的代码。目标如下,使用String对象的适当方法来确定字符串是否存在于搜索字符串中。接下来,如果找到该字符串,则使用找到该字符串的索引位置提醒用户。最后,如果找不到该字符串,请向用户提供相应的消息。目前,我知道match()
方法不是他们要求的方法,因此我将其更改为test()
方法。话虽如此,我无法弄清楚为什么当点击搜索按钮时,没有任何反应,甚至没有错误或其他任何事情。
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lesson 6 Application Project A</title>
<script language="JavaScript" type=text/javascript>
<!--
/*****************************************************************************
The placeholders sub and string are used to pass as arguments the
user's entry into the text box and the textarea. The variable where
is assigned the result of a method which returns the index (integer)
of the first occurence of sub (the string the program is searching for).
Start the search at the beginning of string (the text that is being searched).
Since the string is zero based, add 1 is to get the correct position of sub.
*****************************************************************************/
function search(sub, string) {
var where = string;
var look = new RegExp(sub);
if (look === true){
alert("Your index position is: " + look);
}
else
{
alert("Your string was not found!");
}
}
document.write(look.search(where));
//-->
</script>
</head>
<body>
<h3>CIW JavaScript Specialist</h3>
<hr />
<form name="myForm">
<p>
<strong>Look for:</strong>
<input type="text" name="what" size="20" />
</p>
<p>
<strong>in this string:</strong>
<textarea name="toSearch" rows="4" cols="30" wrap="virtual">
</textarea>
</p>
<p>
<input type="button" value="Search" onclick="search(myForm.what.value, myForm.toSearch.value);" />
</p>
</form>
</body>
</html>