Last active
July 22, 2017 18:36
-
-
Save AllThingsSmitty/5abeef52ebcf613c16a3 to your computer and use it in GitHub Desktop.
Using String.replace() with regular expressions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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