繁体   English   中英

替换并获取单词出现次数

[英]Replace and get word occurrence count

我有一个字符串,我想替换特定的单词,也想计算出现的次数。 例如

"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>');

这将用<b>source</b>替换所有source ,但我也希望source的出现数也就是2

在进行替换调用之前,您可以简单地执行以下操作:

 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)
   };

}

类似于此功能。

现在计数将是

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;

和新的字符串将是

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

为什么不拆分并加入?

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>");

您可以先计算这样的发生次数

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

然后更换它们

replace不能返回2个值(被替换的字符串被替换的计数)。

但是,您可以使用计数器回调函数中对其进行递增

 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