Created
April 18, 2021 14:03
-
-
Save AlexMercedCoder/bbf87033d27c96987349759cc72d940c to your computer and use it in GitHub Desktop.
Pattern Matching Javascript
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
// 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