sub :: String |
Unlike gsub(), 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, sub() works just like 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 = ' ';
markdown.sub(/!\[(.*?)\]\((.*?)\)/, function(match){ return '<img alt="' + match[1] + '" src="' + match[2] + '" />'; }); // -> '<img alt="a pear" src="/img/pear.jpg" /> '
markdown.sub(/!\[(.*?)\]\((.*?)\)/, '<img alt="#{1}" src="#{2}" />'); // -> '<img alt="a pear" src="/img/pear.jpg" /> '
Note
Do not use the "g" flag on the regex as this will create an infinite loop. |
Prototype API 1.5.0 - prototypejs.org