I have a HTML form
Where it takes the user input in text box like Discover then from Textarea box it will print
line number with Text

**Html code :**

```
<div>search</div>
<input type="text" id="needle" value="throw">
<div>this text</div>
<textarea id="haystack">Twenty years from now
you will be more disappointed 
by the things that you didn't 
do than by the ones you did do, 
so throw off the bowlines, 
sail away from safe harbor, 
catch the trade winds in your 
sails. Explore, Dream, Discover. 
    —Mark Twain
</textarea>
<input type="submit" value="Check" onClick="searchText()"> <br><br>
<div>results</div>
<textarea id="output"></textarea>

```

**Javascript :**

```
function searchText(){
// If you want to find the line number for a specific match you need to know it index
    function lineNumberByIndex(index,string){
        // RegExp
        var line = 0,
            match,
            re = /(^)[\S\s]/gm;
        while (match = re.exec(string)) {
            if(match.index > index)
                break;
            line++;
        }
        return line;
    }
    // if you want to find the first index of a match
    function lineNumber(needle,haystack){
        return lineNumberByIndex(haystack.indexOf(needle),haystack);
    }
    // if you want an array of matches
    function lineNumbers(needle,haystack){
        if(needle !== ""){
            var i = 0,a=[],index=-1;
            while((index=haystack.indexOf(needle, index+1)) != -1){
                a.push(lineNumberByIndex(index,haystack));
            }
            return a;
        }
    }
    function update(){
        var needle = $('#needle').val();
        var haystack = $('#haystack').val();
        var output = $("#output").val();
        var nums = lineNumbers(needle,haystack);
        var s = "\"" + needle + "\" is on lines " + nums.join(',') + "\n";
        if(nums.length)
            $("#output").val(s + output);
        else
            $("#output").val("-\n" + output);
    }
    $("input,textarea.input").on("input",update);
    update()
}

```

**.css**

```
* {font:1em arial}
input {width:400px;;padding:5px}
textarea {width:400px;height:200px;padding:5px;}

```

I have to call by creating Button click but it prints abnormal text , if i remove the search text and re enter any other text on button click the text appears n number of times

How to write code which could search for text and print its line number and text

**Code taken from here :** <http://jsfiddle.net/pcmxw37d/>

Abnormal Output :

```
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6
"harbor" is on lines 6

```