instance method String#gsub

View source on GitHub →

String#gsub(pattern, replacement) → String

Returns the string with every occurence of a given pattern replaced by either a regular string, the returned value of a function or a Template string. The pattern can be a string or a regular expression.

If its second argument is a string String#gsub works just like the native JavaScript method replace() set to global match.

var mouseEvents = 'click dblclick mousedown mouseup mouseover mousemove mouseout';
 mouseEvents.gsub(' ', ', ');
// -> 'click, dblclick, mousedown, mouseup, mouseover, mousemove, mouseout'
 mouseEvents.gsub(/\s+/, ', ');
// -> 'click, dblclick, mousedown, mouseup, mouseover, mousemove, mouseout'

If you pass it a function, it will be invoked for every occurrence of the pattern with the match of the current pattern as its unique argument. Note that this argument is the returned value of the match() method called on the current pattern. It is in the form of an array where the first element is the entire match and every subsequent one corresponds to a parenthesis group in the regex.

mouseEvents.gsub(/\w+/, function(match){ return 'on' + match[0].capitalize() });
// -> 'onClick onDblclick onMousedown onMouseup onMouseover onMousemove onMouseout'
 var markdown = '![a pear](/img/pear.jpg) ![an orange](/img/orange.jpg)';
 markdown.gsub(/!\[(.*?)\]\((.*?)\)/, function(match) {
  return '<img alt="' + match[1] + '" src="' + match[2] + '" />';
});
// -> '<img alt="a pear" src="/img/pear.jpg" /> <img alt="an orange" src="/img/orange.jpg" />'

Lastly, you can pass String#gsub a Template string in which you can also access the returned value of the match() method using the ruby inspired notation: #{0} for the first element of the array, #{1} for the second one, and so on. So our last example could be easily re-written as:

markdown.gsub(/!\[(.*?)\]\((.*?)\)/, '<img alt="#{1}" src="#{2}" />');
// -> '<img alt="a pear" src="/img/pear.jpg" /> <img alt="an orange" src="/img/orange.jpg" />'

If you need an equivalent to String#gsub but without global match set on, try String#sub.

Note

Do not use the "g" flag on the regex as this will create an infinite loop.