JavaScript String gsub


/ Published in: JavaScript
Save to your folder(s)

Based on Prototype JS String#gsub


Copy this code and paste it in your HTML
  1. function gsub(source, pattern, replacement) {
  2. var result = '', match, replaced;
  3. while (source.length > 0) {
  4. if (match = source.match(pattern)) {
  5. result += source.slice(0, match.index);
  6. replaced = replacement(match);
  7. result += replaced == null ? '' : String(replaced);
  8. source = source.slice(match.index + match[0].length);
  9. } else {
  10. result += source, source = '';
  11. }
  12. }
  13. return result;
  14. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.