简体   繁体   English

替换并获取单词出现次数

[英]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 . 这将用<b>source</b>替换所有source ,但我也希望source的出现数也就是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 . replace不能返回2个值(被替换的字符串被替换的计数)。

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"/> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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