%% date:: [[2023-05-08]] parent:: %% # [[Regular expressions in js]] [[Regular Expressions]] in [[JavaScript]] are used to search for substrings within a string when you don't know the exact values and instead just know the pattern. ## Defining the regular expression The regular expression is the pattern you're looking for, so start by describing that. There are a whole bunch of symbols to learn, [so here's a cheat sheet I found](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Cheatsheet). For example: ```javascript const regex = /S(\d+)/g; ``` The line above is defining a pattern that would match with something like this: `S83`. ## Finding what matches: `match()` `match()` is the method that looks for something in the string that matches the regular expression. ```javascript const filepath = "Wildemount/_Tues Wildemount DM Notes/Previous Session Notes/S83 2023-Etwas" const regex = /S(\d+)/g; const found = filepath.match(regex); let lastGameNum = found[0].replace("S",""); // 83 ``` `match()` returns an [[Iterating through elements in an array in js|array]] of all the elements that matched the regular expression. In the example above, `found[0]` is `S83`. ## Finding the index of what matches: `search()` ```javascript const filepath = "Wildemount/_Tues Wildemount DM Notes/Previous Session Notes/S83 2023-Etwas" const regex = /S(\d+)/g; const foundIndex = filepath.search(regex); // 60 ```