Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
129
rated 0 times [  132] [ 3]  / answers: 1 / hits: 23589  / 9 Years ago, mon, september 7, 2015, 12:00:00

I have this html code here:



<p id = str>How much wood could a wood chip chop</p>
<br>
<input type = text value = id = txt1/>
<button onclick = myFunction()> Search </button>

<p id=demo>Display the result here.</p>


and a javascript code here:



function myFunction()
{
var myString = document.getElementById(str).innerHTML;
var myWord = document.getElementById(txt1).value;
var myPattern = new RegExp('.'+myWord,'g');

var myResult = myString.split( );

for(var i=0; i<myResult.length; i++) {
var result = myResult[i].match(myPattern);
if(result) break;
}

document.getElementById(demo).innerHTML = myResult;

}


Now what I want to do here is that:




  1. when the user inputs woo it would output wood together with the number of results found like - 2 results found.


  2. when the user inputs od it would also output wood together with the number of results found like - 2 results found.


  3. Same with ch - which the output should be chip, chop - 2 results found.


  4. And with op - which the output should be chop - 1 result found.



More From » html

 Answers
23

Never call functions from onclick HTML attribute, use events instead. Please, refer to this SO question. I have replaced this call with jQuery click function - you may use vanilla JS methods if you prefer.



Your code is almost working. You can simply use RegExp match method to find count of occurences in a string. You don't need to do this manually.



This code works for me:



var myString = document.getElementById(str).innerHTML;
var myWord = document.getElementById(txt1).value;
var myPattern = new RegExp('(\w*'+myWord+'\w*)','gi');

var matches = myString.match(myPattern);

if (matches === null)
{
document.getElementById(demo).innerHTML = No results; // Any message or empty
return;
}

document.getElementById(demo).innerHTML = matches + - + matches.length + result(s) found.;


Here is the working JSFiddle Demo.


[#65164] Friday, September 4, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brynneg

Total Points: 205
Total Questions: 111
Total Answers: 112

Location: Djibouti
Member since Wed, Dec 8, 2021
3 Years ago
;