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
  • 1,042
  • 4
  • 15
  • 40
  • 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
  • 33,467
  • 12
  • 59
  • 101
  • 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
3

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

Here's a beast:

/**
 * @param {string} sel Selector to match 
 * @param {HTMLElement} par (Optional) Parent element | document
 * @returns {HTMLElement} the matched Element by selector
 */
const el = (sel, par) => (par || document).querySelector(sel);

/**
 * @param {string} str String to RegExp escape 
 * @returns {string} String with special RegExp chars escaped
 */
const regEsc = (str) => str.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");

/**
 * @param {string} str String to search in text
 * @param {string} text 
 * @returns {array} Word/s with bold characters (that match str)
 */
const getPortions = (str, text) => {
  const results = [];
  str = str.trim(); // Remove wrapping whitespaces
  if(str.length > 0) {
    const rgxp = new RegExp("(\\S*)?("+ regEsc(str) +")(\\S*)?", "ig");
    text.replace(rgxp, function(match, $1, $2, $3){
      results.push(`${$1||""}<b>${$2}</b>${$3||""}`);
    });
  }
  return results;
};


// The task:

const elString  = el("#string"); 
const elSearch  = el("#search"); 
const elResult  = el("#result"); 

elSearch.addEventListener("input", () => {
  const result = getPortions(elSearch.value, elString.textContent);
  elResult.innerHTML =
    !elSearch.value ?
    `` :
    `<i>Found ${result.length} results:</i><br> ${result.join("<br>")}`; 
});
#result b { color: red; }
<p id="string">How much wood could a wood chip chop</p>
<input id="search" type="search" placeholder="Search&hellip;" autosuggestion=off>
<div id="result"></div>
  • 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

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
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,366
  • 5
  • 18
  • 33
yugi
  • 834
  • 1
  • 15
  • 28