首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >替换并获取单词出现次数

替换并获取单词出现次数
EN

Stack Overflow用户
提问于 2015-12-16 14:32:12
回答 5查看 49关注 0票数 0

我有一个字符串,我想替换特定的单词,还想计算出现的次数。e.g

代码语言:javascript
复制
"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

EN

回答 5

Stack Overflow用户

发布于 2015-12-16 14:35:47

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

代码语言:javascript
复制
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);

票数 1
EN

Stack Overflow用户

发布于 2015-12-16 14:36:55

代码语言:javascript
复制
function replaceAndCount(str, tofind, rep){

   var _x = str.split(tofind);
   return{
     "count":_x.length-1,
     "str":_x.join(rep)
   };

}

类似这样的函数。

现在计数将会是

代码语言:javascript
复制
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;

并且新的字符串将是

代码语言:javascript
复制
var newString = replaceAndCount(str, "source", "<b>source</b>").str.
票数 1
EN

Stack Overflow用户

发布于 2015-12-16 14:34:51

为什么不拆分并加入呢?

代码语言:javascript
复制
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>");
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34305338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档