code_junkie

passing variable to a regexp in javascript

Nov 13th, 2011
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. for(var i = 0; i < agrs.length; i++){
  2.  
  3. reg = new RegExp('{'+i+'}', 'gi');
  4.  
  5. key = key.replace(reg,agrs[i])
  6.  
  7. new RegExp('\{'+i+'\}', 'gi');
  8.  
  9. s='the song says {0} little {1} little {2} little-endians';
  10. args=['zero','one','two'];
  11. new_string = s.replace(/{([0-9]+)}/g, function(wholematch,firstmatch)
  12. {return args[(+firstmatch)]; }
  13. );
  14.  
  15. the song says zero little one little two little-endians
  16.  
  17. s='the song says {0} little {1} little {2} little-endians,n'+
  18. ' {3} little {4} little {5} little-endians';
  19. args=['zero','one','two'];
  20. new_string = s.replace(/{([0-9]+)}/g, function(wholematch,firstmatch)
  21. {var i = +firstmatch; return i < args.length ? args[i] : wholematch;}
  22. );
  23.  
  24. the song says zero little one little two little-endians,
  25. {3} little {4} little {5} little-endians
  26.  
  27. reg = new RegExp('{'+i+'}', 'gi');
Add Comment
Please, Sign In to add comment