如何在JavaScript中打印search()方法的结果?

时间:2016-10-01 00:00:42

标签: javascript methods return document.write

我之前发过一个关于我正在处理的学校问题的问题。我有我相信的任务是正确的功能,但我被卡住了。我需要让代码中的alert()显示它正在搜索的子字符串的索引位置。其他所有工作但我不知道如何将该信息发送回我可以打印到屏幕的变量。我的代码如下:

<!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;

        if (string.search(sub) != -1){
            where = alert("Your index position is: " + where);
        }
        else{
            where = alert("Could not find your string!");
        } 




    }
//-->
</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>

3 个答案:

答案 0 :(得分:1)

试试这个

function search(sub, string) {
    var where = string.indexOf(sub);

    if (where != -1){
        alert("Your index position is: " + where);
    }
    else{
        alert("Could not find your string!");
    } 

}

答案 1 :(得分:0)

你的where变量应该与搜索结果一致。

function search(sub, string) {
        var where = string.search(sub);

        if (where != -1){
            alert("Your index position is: " + (where + 1));
        }
        else{
            alert("Could not find your string!");
        } 
}

答案 2 :(得分:-1)

我对自己问题的解决方法是创建一个名为position的变量,并将其设置为接收子字符串的索引位置。然后我可以将它添加到我的alert()中并将结果显示在屏幕上。更正后的代码如下:

function search(sub, string) {
        var where;
        var position = string.search(sub);

        if (string.search(sub) != -1){
            where = alert("Your index position is: " + position);
        }
        else{
            where = alert("Could not find your string!");
        } 




    }