Last active
September 4, 2021 15:51
-
-
Save ltpitt/2f1c21b61cf6257b344417376e899372 to your computer and use it in GitHub Desktop.
Javascript function that mimics basic GNU/Linux grep command
This file contains 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
/** Function that mimics basic GNU/Linux grep command; | |
* @param {String} multiLineString The multiline string | |
* @param {String} patternToSearch The RegEx pattern to search for | |
* @return {Array} An Array containing all the matching row(s) for patternToSearch in multiLineString | |
*/ | |
function miniGrep(string, patternToSearch) { | |
var regexPatternToSearch = new RegExp("^.*(" + patternToSearch + ").*$", "mg"); | |
match = string.match(regexPatternToSearch); | |
return match; | |
} | |
// Here's an example | |
var multiLineString = "This is a test\nto see if the function\nI am testing works\n"; // Variable containing your multi line string | |
var patternToSearch = "function"; // Variable containing the pattern you are searching in your multi line string | |
console.log(miniGrep(multiLineString, patternToSearch)); // Will return "to see if the function" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment