簡體   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