Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 1st, 2012  |  syntax: None  |  size: 0.82 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Is there a way to add code to each instance of a regex match on the fly?
  2. var i = -1;
  3. myText = myText.replace(/the/gi, function(){ return ++i; });
  4.        
  5. function replaceText(text, splitArg) {
  6.     //var text ="axaxa";
  7.     var parts = text.split(splitArg);
  8.  
  9.     var replaced = "";
  10.     var part;
  11.     for (var i=0;i<parts.length;i++) {
  12.         part = parts[i]
  13.         if(i > 0)
  14.             replaced += i-1;
  15.  
  16.         replaced+=part;
  17.  
  18.     }
  19.     return replaced;
  20. }
  21.  
  22.  
  23. function writeLine(text) {
  24.      document.write("<p>"+text+" &nbsp;</p>");  
  25. }
  26.  
  27. writeLine(replaceText("axa", "x"));
  28. writeLine(replaceText("axaxa", "x"));
  29. writeLine(replaceText("axaxxa", "x"));
  30. writeLine(replaceText("axaxxa", /x+/));//**using a regex!**
  31. writeLine(replaceText("", "x"));
  32. writeLine(replaceText("aa", "x"));
  33.  
  34. //output:
  35. //a0a  
  36. //a0a1a  
  37. //a0a12a  
  38. //a0a1a  
  39. //
  40. //aa