Skip to content

Instantly share code, notes, and snippets.

@AlexMercedCoder
Created April 18, 2021 14:03
Show Gist options
  • Save AlexMercedCoder/bbf87033d27c96987349759cc72d940c to your computer and use it in GitHub Desktop.
Save AlexMercedCoder/bbf87033d27c96987349759cc72d940c to your computer and use it in GitHub Desktop.
Pattern Matching Javascript
// Example String
const stringy = "| ohtml | odiv | Hello World | cdiv | chtml |";
// Function that matches a string against a pattern
const matcher = (str) => {
// declare some variables
let tag;
let split;
// switch statement, if the string matched against regex is true
switch (true) {
case /\so[a-z]*\s/.test(str):
split = str.split("");
tag = split.slice(2, split.length - 1).join("");
return `<${tag}>`;
case /\sc[a-z]*\s/.test(str):
split = str.split("");
tag = split.slice(2, split.length - 1).join("");
return `</${tag}>`;
default:
return str;
}
};
// function that tokenizes/splits string then iterates over tokens assembling parsed string
const parse = (str) => {
const strarray = str.split("|");
let result = "";
for (stry of strarray) {
result += matcher(stry);
}
return result;
};
// Testing the code
console.log(parse(stringy));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment