我有一个字符串,我想要替换特定的单词,并且还要计算出现次数。例如
"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>');
这会将所有source
替换为<b>source</b>
,但我想要source
的出现次数,即2
。
答案 0 :(得分:1)
在替换电话之前,你可以做到:
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);
&#13;
答案 1 :(得分:1)
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.
答案 2 :(得分:0)
为什么不拆分和加入?
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>");
答案 3 :(得分:0)
你可以先计算这样的事件
var occurencies = (string.match(/source/g) || []).length;
然后替换它们
答案 4 :(得分:0)
无法使用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"/>