js keyword highlighting, and the number of times keywords appear

The number of times because the project objective factors of the keyword statistics on the front-end, online to find some information they integrate some code. Suitable for multiple keywords and number of occurrences

On the code:

<body>
<div class="text" style="width: 500px;height: 200px">

</div>
<table>
<thead>
<tr>
<td>关键词</td>
<td>次数</td>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>

</body>

<Script of the type = "text / JavaScript">
var context = "Beijing Forbidden City is China's Ming and Qing dynasties royal palace, formerly known as the Forbidden City, located in the center axis of Beijing, is the essence of Chinese ancient palace architecture." +
"Beijing Forbidden City with three main hall as the center covers an area of 720,000 square meters, construction area of about 150,000 square meters, the size of the palace seventy seats, more than 9,000 houses. "+
" is the world's largest existing best preserved one of the ancient wooden structure building. ";
var words = [" Beijing "," China "," world "];
var countList = new new Array ();
  for (var Word of words) {
// Create a keyword according to regular , where g represents the global match
var new new REG = the RegExp (Word, 'g');
IF (reg.test (context)) {
      keyword is highlighted will appear // process
context = context.replace (reg, '< style = span "Color: Red"> '+ Word +' </ span> ')
// match () method with the indexOf () is similar, except match () returns an array of strings match, noting: n need global 'g'
Otherwise, only to find the first occurrence, if there is no change null string is returned       var COUNT = context.match (REG) .length;
var obj = new new Object ();
obj.key = word;
      length // number of times the data is changed keywords appear
obj.value = COUNT;
countList.push (obj);
}
}
$ ( '. text') HTML (context);.
  
// The results displayed on the table
  var str = '';
  for(var obj of countList){
  str += '<tr>'
  +'<td>' + obj.key + '</td>'
  +'<td>' + obj.value + '</td>'
  +'</tr>'
  }
  $('#tbody').html(str);

</ script>

preview of:

Guess you like

Origin www.cnblogs.com/guofx/p/11135930.html