<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Johnny Turco</title>
    <description>The latest articles on DEV Community by Johnny Turco (@johnnyturco).</description>
    <link>https://dev.to/johnnyturco</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F973808%2F10136f6c-ceab-4146-bfad-dee138c4b4e3.png</url>
      <title>DEV Community: Johnny Turco</title>
      <link>https://dev.to/johnnyturco</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/johnnyturco"/>
    <language>en</language>
    <item>
      <title>How to the Use React Minimal Pie Chart Library</title>
      <dc:creator>Johnny Turco</dc:creator>
      <pubDate>Thu, 16 Feb 2023 22:12:16 +0000</pubDate>
      <link>https://dev.to/johnnyturco/how-to-use-react-minimal-pie-chart-454c</link>
      <guid>https://dev.to/johnnyturco/how-to-use-react-minimal-pie-chart-454c</guid>
      <description>&lt;p&gt;&lt;a href="https://github.com/toomuchdesign/react-minimal-pie-chart" rel="noopener noreferrer"&gt;&lt;code&gt;react-minimal-pie-chart&lt;/code&gt;&lt;/a&gt; is a tiny, lightweight pie charting React library. After reviewing the landscape, &lt;code&gt;react-minimal-pie-chart&lt;/code&gt; is the smallest and simplest way to create pie (or donut) charts for your React app. The following is a quick introduction to get you up and running.&lt;/p&gt;

&lt;p&gt;First, install the library:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install react-minimal-pie-chart
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And import it into your component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { PieChart } from 'react-minimal-pie-chart';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you can use the &lt;code&gt;&amp;lt;PieChart /&amp;gt;&lt;/code&gt; component.&lt;/p&gt;

&lt;p&gt;There are &lt;a href="https://github.com/toomuchdesign/react-minimal-pie-chart#options" rel="noopener noreferrer"&gt;quite a few options&lt;/a&gt; you can use to customize your pie charts. The most basic and important property is the &lt;code&gt;data&lt;/code&gt; property, which takes an array of objects. A basic chart will have the following keys: &lt;code&gt;title&lt;/code&gt;, &lt;code&gt;value&lt;/code&gt;, and &lt;code&gt;color&lt;/code&gt;. For example, your &lt;code&gt;data&lt;/code&gt; attribute might look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data={[
    {
      title: "Test 1",
      value: 50,
      color: "#000000"
    },
    {
      title: "Test 2",
      value: 50,
      color: "#ffffff"
    }
]}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To get your labels to show up, you'll need to add the following property: &lt;code&gt;label={({ dataEntry }) =&amp;gt; dataEntry.title}&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;And to style your labels, you set the &lt;code&gt;labelStyle&lt;/code&gt; property to an object of SVG CSS properties and values. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;labelStyle={{
    fill: "white",
    fontSize: "5px",
    fontFamily: "Helvetica Neue,sans-serif",
    textShadow: "1px 1px 5px #000"
    }}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can also position your labels with &lt;code&gt;labelPosition&lt;/code&gt;, which takes a number 0-100 (for a percent from center).&lt;/p&gt;

&lt;p&gt;Here is a complete example of a basic pie chart component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;PieChart
    label={({ dataEntry }) =&amp;gt; dataEntry.title}
    labelStyle={
        {
            fill: "white",
            fontSize: "5px",
            fontFamily: "Helvetica Neue,sans-serif",
            textShadow: "1px 1px 5px #000"
        }
    }
    labelPosition={75}
    data={
        [
            {
              title: "Test 1",
              value: 50,
              color: "#000000"
            },
            {
              title: "Test 2",
              value: 50,
              color: "#ffffff"
            }
        ]
    }
/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Which will give you a pie chart that looks like this:&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvlyh7a0qr8jl19a7drcf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvlyh7a0qr8jl19a7drcf.png" alt="Image of pie chart example" width="344" height="338"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you want to add more, you can animate your pie chart on component render and even add mouse interactions. Check out the documentation &lt;a href="https://github.com/toomuchdesign/react-minimal-pie-chart" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>mcp</category>
      <category>datascience</category>
    </item>
    <item>
      <title>Using Python to Move the Contents of a Folder to a new Folder</title>
      <dc:creator>Johnny Turco</dc:creator>
      <pubDate>Thu, 16 Feb 2023 18:48:25 +0000</pubDate>
      <link>https://dev.to/johnnyturco/using-python-to-move-the-contents-of-a-folder-to-a-new-folder-3j4k</link>
      <guid>https://dev.to/johnnyturco/using-python-to-move-the-contents-of-a-folder-to-a-new-folder-3j4k</guid>
      <description>&lt;p&gt;Our law firm recently switched to a new client management system and, as part of the migration from our old system, we had to move the contents of clients' files from the old folder to a new folder where the new system would point to. In our case, the old client folders and new folders were placed in the same directory by the migration team, but the contents still needed to be moved. Additionally, while the old folders were named after a client's account number, the new folders had the account number and the client's name. Here's a fake, but representative, example of the parent directory:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg46ks6rjbxa1238all9a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg46ks6rjbxa1238all9a.png" alt="Screenshot of parent directory" width="800" height="545"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I have been wanting to explore Python recently and thought this would be a great opportunity to learn.&lt;/p&gt;

&lt;p&gt;To start, I needed to import some modules:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import shutil
import os
import re
from pathlib import Path
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, I needed the path to the parent directory of the client folders; in my case, "Test Directory":&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;source = 'Users/johnnyturco/Downloads/Test Directory'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note: This is a string of a macOS path; if you're on Windows, you will need to use the appropriate path with back slashes (&lt;code&gt;\&lt;/code&gt;). Also, &lt;code&gt;\&lt;/code&gt; is a special character in Python, so you need to "escape" it with another &lt;code&gt;\&lt;/code&gt;. To make this platform-independent, you could use &lt;a href="https://docs.python.org/3/library/os.path.html#os.path.join" rel="noopener noreferrer"&gt;&lt;code&gt;os.path.join&lt;/code&gt;&lt;/a&gt;. Because only I will be running this script and it will be on a Mac, I decided to keep my code a little more readable and use a string for my source path.&lt;/p&gt;

&lt;p&gt;I also needed a list of the directories &lt;em&gt;inside&lt;/em&gt; of the parent source:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;directories = os.listdir(source)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because the source directory contained both the old (e.g., "2020-0123") and new folders (e.g., "2020-0123 - Smith, John"), I needed a way to target just one of a client's folders. I figured if I targeted the new folder naming convention with a regular expression, I could easily derive the corresponding old folder's name with a regular expression group:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;folder_name_regex = re.compile(r'(^\d{4}-\d{4}) - .*')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For a quick primer on what regular expressions are, check out my &lt;a href="https://dev.to/johnnyturco/what-are-regular-expressions-using-a-simple-javascript-regular-expression-to-format-phone-numbers-2cgh"&gt;blog post&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Putting all that together with the for-loop:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for directory in directories:
    if folder_name_regex.search(directory):
        account_number = folder_name_regex.search(directory).group(1)
        dir_source = source + account_number
        dir_target = source + directory
        files = os.listdir(dir_source)
        for file in files:
            shutil.move(os.path.join(dir_source, file),
                        os.path.join(dir_target, file))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let me explain what's going on here. For each directory inside the parent source, check if the directory matches a regular expression that would return something like "2020-0123 - Smith, John" (as opposed to its counterpart, "2020-0123"). From the regular expression, get the account number and assign it to a variable. Use that variable to make the path to the old source folder (2020-0123); assign it to &lt;code&gt;dir_source&lt;/code&gt;. Create a path to the new destination, &lt;code&gt;dir_target&lt;/code&gt; (2020-0123 - Smith, John). Finally, get a list of all the files and folders in the source folder (2020-0123), loop over each file/folder, and move it from the source to the target.&lt;/p&gt;

&lt;p&gt;Here's all of the code together:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import shutil
import os
import re

from pathlib import Path

source = '/Users/johnnyturco/Downloads/Test Directory/'

directories = os.listdir(source)

folder_name_regex = re.compile(r'(^\d{4}-\d{4}) - .*')

for directory in directories:
    if folder_name_regex.search(directory):
        account_number = folder_name_regex.search(directory).group(1)
        dir_source = source + account_number
        dir_target = source + directory
        files = os.listdir(dir_source)
        for file in files:
            shutil.move(os.path.join(dir_source, file),
                        os.path.join(dir_target, file))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>microservices</category>
      <category>backenddevelopment</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Intro to React Context</title>
      <dc:creator>Johnny Turco</dc:creator>
      <pubDate>Mon, 09 Jan 2023 20:05:04 +0000</pubDate>
      <link>https://dev.to/johnnyturco/intro-to-react-context-58g9</link>
      <guid>https://dev.to/johnnyturco/intro-to-react-context-58g9</guid>
      <description>&lt;p&gt;React Context is a React hook that allows you to manage state globally. &lt;a href="https://www.w3schools.com/react/react_usecontext.asp" rel="noopener noreferrer"&gt;Per W3Schools&lt;/a&gt;, "[React Context] can be used together with the useState Hook to share state between deeply nested components more easily than with useState alone." Instead of "prop drilling" (passing state via props through your component hierarchy), you can use Context to pass state through children components.&lt;/p&gt;

&lt;h2&gt;
  
  
  Getting Started: Creating Context
&lt;/h2&gt;

&lt;p&gt;To get started, import &lt;code&gt;createContext&lt;/code&gt; (and &lt;code&gt;useState&lt;/code&gt;):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createContext, useState } from "react"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then initialize &lt;code&gt;createContext&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const FoodContext = createContext()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, wrap the components you want to have access to the context in the Context Provider with the value of your state:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function App() {
    const [food, setFood] = useState({
        name: "Pho",
        cuisine: "Vietnamese",
        portion: 1
    })

    return (
        &amp;lt;FoodContext.Provider value={food}&amp;gt;
            &amp;lt;ChildComponent /&amp;gt;
        &amp;lt;/FoodContext.Provider&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Using Context
&lt;/h2&gt;

&lt;p&gt;Now that you've created your Context, you'll need to use the &lt;code&gt;useContext&lt;/code&gt; hook in your child component(s) to access it. Start by importing &lt;code&gt;useContext&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useContext } from "react"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, you can use useContext throughout your child component(s)!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function ChildComponent() {
    const food = useContext(FoodContext)

    return (
        &amp;lt;h1&amp;gt;{My Favorite is: ${food.name}}&amp;lt;/h1&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Updating State in Child Components
&lt;/h2&gt;

&lt;p&gt;In addition to passing state as the value in your Context Provider, you can also include the setter function to update state from child components. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;FoodContext.Provider value={{ food, setFood }}&amp;gt;
    &amp;lt;ChildComponent /&amp;gt;
&amp;lt;/FoodContext.Provider&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, in your child component, you have access to the state and the setter function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function ChildComponent() {
    const { food, setFood } = useContext(FoodContext)

    if (food.name === "Pho") {
        setFood((previousFood) =&amp;gt; {
            return {
                ...previousFood,
                name: "Bánh mì"
            }
        })
    }

    return (
        &amp;lt;h1&amp;gt;{My Favorite is: ${food.name}}&amp;lt;/h1&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;React Context allows your child components to easily access data from a parent. Depending on how deep your component hierarchy is, Context can be a simpler way to pass data through your component tree than passing data as props.&lt;/p&gt;

</description>
      <category>gratitude</category>
    </item>
    <item>
      <title>What Are Regular Expressions? A Simple JavaScript Regex to Format Phone Numbers</title>
      <dc:creator>Johnny Turco</dc:creator>
      <pubDate>Fri, 09 Dec 2022 16:36:49 +0000</pubDate>
      <link>https://dev.to/johnnyturco/what-are-regular-expressions-using-a-simple-javascript-regular-expression-to-format-phone-numbers-2cgh</link>
      <guid>https://dev.to/johnnyturco/what-are-regular-expressions-using-a-simple-javascript-regular-expression-to-format-phone-numbers-2cgh</guid>
      <description>&lt;p&gt;You're probably already familiar with using Command + F (or Control + F on PC) to search for text on a web page or PDF. This command will only find &lt;em&gt;exact&lt;/em&gt; matches, however. Regular expressions, on the other hand, allow you to specify &lt;em&gt;patterns&lt;/em&gt; to search for. For example, if you know a string of text contains an email address, but you don't know what the address is, you could find it by specifying a pattern based on how email addresses are structured. At a basic level, all email addresses have:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Some combination of letters and numbers (and possibly a few special characters, like periods, underscores, etc.—but let's keep it simple for now);&lt;/li&gt;
&lt;li&gt;An @ sign;&lt;/li&gt;
&lt;li&gt;Another combination of letters and numbers for the domain;&lt;/li&gt;
&lt;li&gt;A period preceding the top-level domain; and&lt;/li&gt;
&lt;li&gt;A top-level domain.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;What if we could search based on these &lt;em&gt;criteria&lt;/em&gt; instead of 1-for-1 matches? That's exactly what regular expressions allow you to do.&lt;/p&gt;

&lt;p&gt;The term regular expression (often shortened to regex or regexp) is generic; there are several variations, but the syntax remains relatively consistent across the many implementations. Many of the resources you will find online will be applicable to the majority of implementations. This article is a simple introduction to what regular expressions are and what they can do, and I'll illustrate it with a real-world application I used.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example: Formatting Phone Numbers
&lt;/h2&gt;

&lt;p&gt;I was recently working with an API that returned (U.S.) phone numbers as a 10-digit string (e.g., 5557071234), and I needed a way to convert these numbers into a more readable format, like (555) 707-1234.  Here's how I did it in JavaScript:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let phoneNumber = "5557071234"
console.log(phoneNumber.replace(/(\d{3})(\d{3})(\d{4})/,'($1) $2-$3'))
// output: (555) 707-1234
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's break-down what's happening here. Note: the &lt;code&gt;replace&lt;/code&gt; method &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace" rel="noopener noreferrer"&gt;syntax&lt;/a&gt; is &lt;code&gt;replace(pattern, replacement)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;/(\d{3})(\d{3})(\d{4})/&lt;/code&gt; is the &lt;code&gt;pattern&lt;/code&gt; parameter in our example. Note that in JavaScript, regular expressions are surrounded by slashes. The regular expression itself is &lt;code&gt;(\d{3})(\d{3})(\d{4})&lt;/code&gt;. Ignore the parentheses for now; focus on &lt;code&gt;\d{3}\d{3}\d{4}&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;\d&lt;/code&gt; matches any digit (0-9)&lt;/li&gt;
&lt;li&gt;The curly brackets that follow the &lt;code&gt;\d&lt;/code&gt; are a type of regular expression quantifier; in this case &lt;code&gt;{3}&lt;/code&gt; specifies exactly three digits.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In plain English, this expressions says, "3 digits, followed by 3 digits, followed by 4 digits," which is really the same as saying, "10 digits," or &lt;code&gt;\d{10}&lt;/code&gt;. Both would match "5557071234". Let's add the parenthesis back in to our expression: &lt;code&gt;(\d{3})(\d{3})(\d{4})&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Parentheses in regular expressions create &lt;em&gt;groups&lt;/em&gt;. A group can be referred to with something called a &lt;em&gt;backreference&lt;/em&gt;. Think of it as assigning everything in parentheses to a variable. You can then arrange those variables into the format you want.&lt;/p&gt;

&lt;p&gt;That brings us to the second parameter, the &lt;code&gt;replacement&lt;/code&gt;; &lt;code&gt;'($1) $2-$3'&lt;/code&gt; in our case. This says:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Surround the first group, &lt;code&gt;\d{3}&lt;/code&gt; (i.e., the first 3 digits) in parentheses;&lt;/li&gt;
&lt;li&gt;Add a space;&lt;/li&gt;
&lt;li&gt;Then the second group, &lt;code&gt;\d{3}&lt;/code&gt; (i.e., the next set of 3 digits);&lt;/li&gt;
&lt;li&gt;Add a hyphen;&lt;/li&gt;
&lt;li&gt;Then the third group &lt;code&gt;\d{4}&lt;/code&gt; (i.e., the next set of 4 digits)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The result from our example: (555) 707-1234, where "555" is group 1, "707" is group 2, and "1234" is group 3.&lt;/p&gt;

&lt;h3&gt;
  
  
  Limitations
&lt;/h3&gt;

&lt;p&gt;This regular expression works well because I know my data source contains &lt;em&gt;only&lt;/em&gt; 10-digit strings. That removes a lot of variables that I'd otherwise need to account for. For example, if the data source included country codes, the replacement would be off (e.g., "15557071234" would be replaced with (155) 570-7123).&lt;/p&gt;

&lt;p&gt;Additionally, this regular expression assumes no special characters were in the data source. If there were, you could start by writing a regular expression to find and remove all special characters before using our formatting regular expression.&lt;/p&gt;

&lt;p&gt;For our purposes, though, this regex is a simple demonstration to explain how regular expressions work.&lt;/p&gt;

&lt;h2&gt;
  
  
  Resources
&lt;/h2&gt;

&lt;p&gt;We only looked at a couple regex commands, but there are a lot more. I would recommend keeping a cheatsheet on hand. Here's the one I use, based on a &lt;a href="https://medium.com/@qdangdo/regex-a-way-to-match-any-pattern-of-string-1dd327130fc6" rel="noopener noreferrer"&gt;blog post by Quang Do&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.       - Any Character Except New Line
\d      - Digit (0-9)
\D      - Not a Digit (0-9)
\w      - Word Character (a-z, A-Z, 0-9, _)
\W      - Not a Word Character
\s      - Whitespace (space, tab, newline)
\S      - Not Whitespace (space, tab, newline)

\b      - Word Boundary
\B      - Not a Word Boundary
^       - Beginning of a String
$       - End of a String

[]      - Matches Characters in brackets
[^ ]    - Matches Characters NOT in brackets
|       - Either Or
( )     - Group

Quantifiers:
*       - 0 or More
+       - 1 or More
?       - 0 or One
{3}     - Exact Number
{3,4}   - Range of Numbers (Minimum, Maximum)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet" rel="noopener noreferrer"&gt;MDN&lt;/a&gt; also has a pretty comprehensive cheatsheet.&lt;/p&gt;

&lt;p&gt;To practice, I recommend &lt;a href="https://regexr.com/" rel="noopener noreferrer"&gt;RegExr&lt;/a&gt;. It does an excellent job of breaking down groups. &lt;a href="https://regex101.com/" rel="noopener noreferrer"&gt;Regex101&lt;/a&gt; is also a great resource.&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>php</category>
    </item>
    <item>
      <title>Focus a Field Using JavaScript KeyboardEvents</title>
      <dc:creator>Johnny Turco</dc:creator>
      <pubDate>Fri, 18 Nov 2022 19:13:31 +0000</pubDate>
      <link>https://dev.to/johnnyturco/focus-a-field-using-javascript-keyboardevents-4f16</link>
      <guid>https://dev.to/johnnyturco/focus-a-field-using-javascript-keyboardevents-4f16</guid>
      <description>&lt;p&gt;If you don't already know, you can press the forward slash key &lt;code&gt;/&lt;/code&gt; on Gmail, YouTube, and Google search result pages to focus your cursor back to the search field. I'll show you how you can implement this on your website with JavaScript, and a few things to look out for.&lt;/p&gt;

&lt;p&gt;First, you'll need reference to the search field you want to focus, in my case:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const searchField = document.querySelector('#search-input');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We'll come back to this later.&lt;/p&gt;

&lt;p&gt;Second, you'll need to add an &lt;code&gt;EventListener&lt;/code&gt;. I would suggest adding the &lt;code&gt;EventListener&lt;/code&gt; to the &lt;code&gt;window&lt;/code&gt;  &lt;code&gt;EventTarget&lt;/code&gt; so the keyboard shortcut works anywhere on your webpage:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;window.addEventListener()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, you will need to choose a &lt;code&gt;listener&lt;/code&gt; to listen for your keyboard shortcut. You have a few main choices:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;code&gt;keydown&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;keypress&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;keyup&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You should avoid using &lt;code&gt;keypress&lt;/code&gt; because it has been deprecated, &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event" rel="noopener noreferrer"&gt;per MDN&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;As their names suggest, &lt;code&gt;keydown&lt;/code&gt; fires when the key is pressed and &lt;code&gt;keyup&lt;/code&gt; fires when the key is released. Note that &lt;code&gt;keydown&lt;/code&gt; will continue to fire for as long as the key is held down (&lt;code&gt;keypress&lt;/code&gt; does, too). If you want to avoid the possibility of a bunch of unwanted characters in your focused input area, you may want to use &lt;code&gt;keyup&lt;/code&gt; instead. Interestingly, Google will let you input as many forward slashes as you want if you hold down the key.&lt;/p&gt;

&lt;p&gt;Another behavior to consider is the order the that the &lt;code&gt;listeners&lt;/code&gt; fire. Because &lt;code&gt;keydown&lt;/code&gt; fires on, well, key &lt;em&gt;down&lt;/em&gt;, it fires before &lt;code&gt;keyup&lt;/code&gt;. That difference may be obvious, but it can cause a noticeable delay if your users hold the shortcut key down for longer than a quick press. That said, the difference will probably be imperceptible to most. In my example, though, I'll use &lt;code&gt;keyup&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;window.addEventListener('keyup', (event) =&amp;gt; {
    // code
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;KeyboardEvent&lt;/code&gt; objects have a number of important &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#instance_properties" rel="noopener noreferrer"&gt;properties&lt;/a&gt;. You can use &lt;code&gt;.code&lt;/code&gt; or &lt;code&gt;.key&lt;/code&gt; to specify which key to act on. MDN makes an important note about &lt;code&gt;.code&lt;/code&gt;: this property ignores keyboard layout; it returns the code for the physical key location. So, if you have users that may be using Dvorak or other non-QWERTY keyboard layouts, you may need to consider how that affects their experience.&lt;/p&gt;

&lt;p&gt;To determine which &lt;code&gt;.code&lt;/code&gt; value corresponds to which character, check out &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_code_values" rel="noopener noreferrer"&gt;this MDN doc&lt;/a&gt;. A list of &lt;code&gt;.key&lt;/code&gt; values is provided &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values" rel="noopener noreferrer"&gt;at this doc&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Combining &lt;code&gt;.code&lt;/code&gt; and all of the above with an &lt;code&gt;if&lt;/code&gt; statement gets us a basic implementation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const searchField = document.querySelector('#search-input');
window.addEventListener('keyup', (event) =&amp;gt; {
  if(event.code === 'Slash'){
    searchField.focus();
  }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;.focus()&lt;/code&gt; method focuses on the query selector we made in the first step.&lt;/p&gt;

&lt;p&gt;There are a couple of other things we can add, though—some of which will be a matter of preference or depend on your implementation.&lt;/p&gt;

&lt;p&gt;First, if your website has another text input besides your search field, you may want to disable the &lt;code&gt;/&lt;/code&gt; shortcut (or whatever you set your shortcut key to) when entering text in the other input field. To do that, we first need to know what element the user is currently focused on, which can accomplished with the &lt;code&gt;.activeElement&lt;/code&gt; property on the document.&lt;/p&gt;

&lt;p&gt;We also need to know the name of the tag of the active element, which we can find with the aptly named &lt;code&gt;.tagName&lt;/code&gt; property. Note that &lt;code&gt;.tagName&lt;/code&gt; will return the element's tag name in all caps (e.g., an &lt;code&gt;&amp;lt;input&amp;gt;&lt;/code&gt; tag will be returned as &lt;code&gt;INPUT&lt;/code&gt;). Combined with &lt;code&gt;.activeElement&lt;/code&gt;, the code looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;document.activeElement.tagName
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Combined with our existing &lt;code&gt;if&lt;/code&gt; statement, your code should look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const searchField = document.querySelector('#search-input');
window.addEventListener('keyup', (e) =&amp;gt; {
  if((e.code === 'Slash') &amp;amp;&amp;amp; (document.activeElement.tagName !== 'INPUT')){
    searchField.focus();
  }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you're checking if your user is already in a text input field, you'll probably also want to check if the user is in a &lt;code&gt;textarea&lt;/code&gt; field. You can accomplish this in the same way as above:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;document.activeElement.tagName !== 'TEXTAREA'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In total, the final product looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const searchField = document.querySelector('#search-input');
window.addEventListener('keyup', (e) =&amp;gt; {
  if((e.code === 'Slash') &amp;amp;&amp;amp; (document.activeElement.tagName !== 'INPUT') &amp;amp;&amp;amp; (document.activeElement.tagName !== 'TEXTAREA')){
    searchField.focus();
  }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Bonus: You may also want to check if your user is in an element that has the &lt;code&gt;contenteditable&lt;/code&gt; HTML attribute enabled. The process to check is a little different, but also more straightforward with the &lt;code&gt;.isContentEditable&lt;/code&gt; property. The property returns &lt;code&gt;true&lt;/code&gt; if the contents are editable and &lt;code&gt;false&lt;/code&gt; if not. &lt;code&gt;contenteditable&lt;/code&gt; is of course less common than text inputs and text areas, but it's worth noting.&lt;/p&gt;

</description>
      <category>javascript</category>
    </item>
  </channel>
</rss>
