我有一个字符串,我想替换特定的单词,还想计算出现的次数。e.g
"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。
发布于 2015-12-16 14:35:47
在调用replace之前,您可以简单地执行以下操作:
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);
发布于 2015-12-16 14:36:55
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.发布于 2015-12-16 14:34:51
为什么不拆分并加入呢?
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>");https://stackoverflow.com/questions/34305338
复制相似问题