Skip to content

Instantly share code, notes, and snippets.

@ltpitt
Last active September 4, 2021 15:51
Show Gist options
  • Save ltpitt/2f1c21b61cf6257b344417376e899372 to your computer and use it in GitHub Desktop.
Save ltpitt/2f1c21b61cf6257b344417376e899372 to your computer and use it in GitHub Desktop.
Javascript function that mimics basic GNU/Linux grep command
/** 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