1

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.

Makudex
  • 962
  • 4
  • 14
  • 39
  • 2
    Never call functions from `onclick` HTML attribute, use events instead. Please, refer to this SO question: http://stackoverflow.com/questions/17378199/uncaught-referenceerror-function-is-not-defined-with-onclick – Yeldar Kurmangaliyev Sep 07 '15 at 05:14
  • @ Yeldar Kurmangaliyev Thanks for the advise. Much appreciated. I'll try to update it after that problem is solved. – Makudex Sep 07 '15 at 05:17
  • @ Ashad Shanto, I tried using it as you can see in the above code but it only worked when you input the last strings of the word and not with the first strings. – Makudex Sep 07 '15 at 05:19
  • See how it's done here: http://stackoverflow.com/questions/31830945/truncate-text-preserving-keywords/31833249 – Roko C. Buljan Sep 07 '15 at 05:26

4 Answers4

5

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.

Community
  • 1
  • 1
Yeldar Kurmangaliyev
  • 32,279
  • 11
  • 59
  • 94
  • 1
    regex should be something like `new RegExp('([a-z0-9]*'+myWord+'[a-z0-9]*)','gi')` to get the full word – Jorg Sep 07 '15 at 05:21
  • 1
    By the way, `ch` returns 3 because it is `chip`, `chop`, `much`. – Yeldar Kurmangaliyev Sep 07 '15 at 05:21
  • 3
    @Jorg You can just use `\\w` other than `[a-z0-9]`. – Spencer Wieczorek Sep 07 '15 at 05:22
  • It can only get the number of results found, not the word referring to that results. As stated in the above question, i also wanted to have an output of the results in the searched string. – Makudex Sep 07 '15 at 05:23
  • Thanks! It worked now.. but when i search something not in the sentence it doesn't delete the result. Please help me with this one. – Makudex Sep 07 '15 at 05:26
  • @wwwDELL You can simply check for `matches` being `null`. I have updated it once again. – Yeldar Kurmangaliyev Sep 07 '15 at 05:28
  • This will fail if `myWord` contains special regexp characters. Also, the parentheses in your regxp are not necessary. –  Sep 07 '15 at 05:34
  • @torazaburo That's just the minimal example answering the OP's question. It will also produce unexpected results if you enter an empty string - if such cases are possible, then you will need to check them. – Yeldar Kurmangaliyev Sep 07 '15 at 05:36
  • @YeldarKurmangaliyev you're missing to prevent an empty query. Here's a workaround: http://jsfiddle.net/qur67s9d/6/ – Roko C. Buljan Sep 07 '15 at 05:48
2

I would prefer to break the sentence into words:

var words = myString.split(' ');

Now filter the words which contain the text being sought:

words = words.filter(function(word) {
  return word.indexOf(myWord) !== -1;
}

Then print them out or insert in the DOM or whatever:

result = words.join(',') + " - " + words.length + " result(s) found";
document.getElementById("demo".textContent = result;
1

Here's a beast:

var string  = document.getElementById("str").innerHTML;
var elDemo  = document.getElementById("demo"); 

function getPortions(queryString, string) {
  var results = [];
  if(queryString.length > 0){
    var rgxp = new RegExp("(\\S*)?("+ queryString +")(\\S*)?", "ig");
    string.replace(rgxp, function(match, $1, $2, $3){
      results.push( ($1||"") +"<b>"+ $2 +"</b>"+ ($3||"") );
    });
  }
  return results;
}

document.getElementById("txt1").addEventListener("input", function(){
  var result = getPortions(this.value, string);
  elDemo.innerHTML = "Found "+ result.length +" results<br>"+ result.join("<br>"); 
});
b{color:red;}
<p id="str">How much wood could a wood chip chop</p>
<input type="text" id="txt1"/>
<p id="demo">Found 0 results</p>
  • it returns the results results length,
  • bolded portions of characters,
  • you don't need a Button to start the search.

Basically it's a remake of this answer: Truncate text preserving keywords

Community
  • 1
  • 1
Roko C. Buljan
  • 180,066
  • 36
  • 283
  • 292
0

try this one

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

     var myResult = myString.split(" ");
    var innerHtmml="";
    var count=0;

  for(var i=0; i<myResult.length; i++) {
    var result = myResult[i].match(myPattern);
    if(result) {
        alert(myResult[i]);
        innerHtmml=myResult[i]+","; 
      count++;
    }
  }

  document.getElementById("demo").innerHTML = myResult;

}
Muhammad Usman
  • 1,352
  • 4
  • 16
  • 31
yugi
  • 774
  • 14
  • 26