简体   繁体   中英

Replace and get word occurrence count

I have a string, I want to replace the specific word and also want to count the number of occurrence. eg

"Of course, there are many other open source or commercial tools available.
Twitter typeahead is probably the most important open source alternative."
.replace(/source/g,'<b>source</b>');

This will replace all source with <b>source</b> but I want the count of occurance of source also ie 2 .

Before the replace call you can simply do:

 var count = ("Of course, there are many other open source or commercial tools available. Twitter typeahead is probably the most important open source alternative.".match(/source/g) || []).length; var replaceString = "Of course, there are many other open source or commercial tools available.Twitter typeahead is probably the most important open source alternative." .replace(/source/g,'<b>source</b>'); alert(count); alert(replaceString); 

function replaceAndCount(str, tofind, rep){

   var _x = str.split(tofind);
   return{
     "count":_x.length-1,
     "str":_x.join(rep)
   };

}

Something like this function.

Now the count will be

var str = "Of course, there are many other open source or commercial tools available.
Twitter typeahead is probably the most important open source alternative.";
var count = replaceAndCount(str, "source", "<b>source</b>").count;

and new string will be

var newString = replaceAndCount(str, "source", "<b>source</b>").str.

why not split and join?

function replaceAndCount( str, toBeReplaced, toBeReplacedBy )
{
  var arr = str.split( "toBeReplaced" );

  return [ arr.join( toBeReplacedBy  ), arr.length ];
}  

replaceAndCount( "Of course, there are many other open source or commercial tools available. Twitter typeahead is probably the most important open source alternative." , "source", "<b>source</b>");

you can first count the occurencies like this

var occurencies = (string.match(/source/g) || []).length;

and then replace them

It is not possible to return 2 values (both the replaced string and the replacement count) with replace .

However, you can use a counter and increment it inside a callback function .

 var count = 0; // Declare the counter var res = "Of course, there are many other open source or commercial tools available.Twitter typeahead is probably the most important open source alternative.".replace(/source/g,function(m) { count++; return '<b>source</b>';}); // demo check document.getElementById("r").innerHTML = "Result: " + res; document.getElementById("r").innerHTML += "<br/>Count: " + count; 
 <div id="r"/> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM