0

I have a string, I want to replace the specific word and also want to count the number of occurrence. 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>');

This will replace all source with <b>source</b> but I want the count of occurance of source also i.e 2.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Manish Kumar
  • 10,214
  • 25
  • 77
  • 147

5 Answers5

1

Before the replace call you can simply do:

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);
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1
function replaceAndCount(str, tofind, rep){

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

}

Something like this function.

Now the count will be

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;

and new string will be

var newString = replaceAndCount(str, "source", "<b>source</b>").str.
void
  • 36,090
  • 8
  • 62
  • 107
0

why not split and join?

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>");
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

you can first count the occurencies like this

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

and then replace them

0

It is not possible to return 2 values (both the replaced string and the replacement count) with replace.

However, you can use a counter and increment it inside a callback function.

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"/>
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563