instance method String#sub

View source on GitHub →

String#sub(pattern, replacement[, count = 1]) → String

Returns a string with the first count occurrences of pattern replaced by either a regular string, the returned value of a function or a Template string. pattern can be a string or a regular expression.

Unlike String#gsub, String#sub takes a third optional parameter which specifies the number of occurrences of the pattern which will be replaced. If not specified, it will default to 1.

Apart from that, String#sub works just like String#gsub. Please refer to it for a complete explanation.

Examples
var fruits = 'apple pear orange';
 fruits.sub(' ', ', ');
// -> 'apple, pear orange'
 fruits.sub(' ', ', ', 1);
// -> 'apple, pear orange'
 fruits.sub(' ', ', ', 2);
// -> 'apple, pear, orange'
 fruits.sub(/\w+/, function(match){ return match[0].capitalize() + ',' }, 2);
// -> 'Apple, Pear, orange'
 var markdown = '![a pear](/img/pear.jpg) ![an orange](/img/orange.jpg)';
 markdown.sub(/!\[(.*?)\]\((.*?)\)/, function(match) {
  return '<img alt="' + match[1] + '" src="' + match[2] + '" />';
});
// -> '<img alt="a pear" src="/img/pear.jpg" /> ![an orange](/img/orange.jpg)'
 markdown.sub(/!\[(.*?)\]\((.*?)\)/, '<img alt="#{1}" src="#{2}" />');
// -> '<img alt="a pear" src="/img/pear.jpg" /> ![an orange](/img/orange.jpg)'
Note

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