Skip to content

Instantly share code, notes, and snippets.

@AllThingsSmitty
Last active July 22, 2017 18:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AllThingsSmitty/5abeef52ebcf613c16a3 to your computer and use it in GitHub Desktop.
Save AllThingsSmitty/5abeef52ebcf613c16a3 to your computer and use it in GitHub Desktop.
Using String.replace() with regular expressions
var myString = 'EXAMPLEstring';
var myNewString = myString.replace(/[A-Z]/g, '0');
console.log(myNewString);
function replaceFunc (a, b, c) {
console.log(a, b, c);
return a.toLowerCase();
}
var myOtherString = myString.replace(/[A-Z]/g, replaceFunc);
console.log(myOtherString);
// Credit: Louis Lazarus
// This function expects three arguments. There could be more depending on how many "capture" groups are included in the regular expression.
// The first argument (a) is always the full text of the match.
// Since there are no capture groups, the second argument (b) is the zero-based index of the match within the string.
// The final argument (c) is the full text of the string being searched.
// As shown in this example, because the match is global (using the "g" identifier in the RegEx), the three arguments are logged for each match.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment