<?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: Rutkat</title>
    <description>The latest articles on DEV Community by Rutkat (@rutkat).</description>
    <link>https://dev.to/rutkat</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%2F667980%2Fabe01bd3-e64e-4b34-a2da-5acd81155fdf.png</url>
      <title>DEV Community: Rutkat</title>
      <link>https://dev.to/rutkat</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rutkat"/>
    <language>en</language>
    <item>
      <title>Get to know React Expo to build Mobile Apps</title>
      <dc:creator>Rutkat</dc:creator>
      <pubDate>Thu, 08 May 2025 05:35:12 +0000</pubDate>
      <link>https://dev.to/rutkat/you-need-to-know-react-expo-to-build-mobile-apps-4b1e</link>
      <guid>https://dev.to/rutkat/you-need-to-know-react-expo-to-build-mobile-apps-4b1e</guid>
      <description>&lt;h2&gt;
  
  
  An intro to mobile app development
&lt;/h2&gt;

&lt;p&gt;In case you want to develop a mobile app very quickly for Android or IOS, this is the guide for you. I'll explain common methods of developing a mobile app and how you can benefit with free tools. The important reasons why you should make a mobile app today are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;To grow your audience reach&lt;/li&gt;
&lt;li&gt;To add another revenue channel for your business&lt;/li&gt;
&lt;li&gt;To improve customer experience and convenience&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Having just a website is okay too, but you will probably want to grow your business sooner or later. Don't worry, we're not going to produce this code with AI just because AI is trending nor do we want AI slop. The goal of this article is to show you the options you how quickly you can deploy a mobile app using React Expo which can be seen at &lt;a href="http://expo.dev" rel="noopener noreferrer"&gt;http://expo.dev&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;As a pre-requisite&lt;/em&gt;, you should have knowledge of the functionality of websites, installing software on Mac or Windows, and using the terminal command line. This is more of a quickstart guide so it's not code heavy.&lt;/p&gt;

&lt;h2&gt;
  
  
  Approach
&lt;/h2&gt;

&lt;p&gt;The first approach is to understand the options available to build mobile apps. The obvious platforms are Android and iOS which have their own unique app ecosystems. The origins of iOS app development started with Objective-C which evolved to Swift and Dart programming languages. For Android, it's Java and Kotlin. Those are known as the native programming languages that get you the best possible performance for mobile device hardware yet are the most intricate to build with. &lt;em&gt;You don't need to use these languages unless you intend to have a full-time Android or iOS development career.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;There are tools and languages available which can convert your website and web app into a mobile app without the hassle of using Java or Swift. The tradeoff is app performance and access to all hardware features if you choose the alternate methods. Those mobile app building methods can be:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;a href="https://reactnative.dev/" rel="noopener noreferrer"&gt;React Native&lt;/a&gt; &amp;amp; &lt;a href="https://expo.dev/" rel="noopener noreferrer"&gt;React Expo&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="https://ionicframework.com/" rel="noopener noreferrer"&gt;Ionic&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://lynxjs.org/" rel="noopener noreferrer"&gt;LynxJS&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://nativescript.org/" rel="noopener noreferrer"&gt;NativeScript&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://flutter.dev/" rel="noopener noreferrer"&gt;Flutter&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://dotnet.microsoft.com/en-us/apps/xamarin" rel="noopener noreferrer"&gt;Xamarin&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So far I've tried building with Ionic, React Native and LynxJS. Follow me @therutkat for my upcoming comparison article. I can tell you that recent changes to the &lt;a href="https://reactnative.dev/blog/2024/10/23/the-new-architecture-is-here" rel="noopener noreferrer"&gt;React Native architecture&lt;/a&gt; have convinced me to follow their path to building an app. They say that the app performance is very near to that of the native coding language. In addition, the React Expo ecosystem for faster testing and deployments for Android+iOS is helps your workflow tremendously. &lt;/p&gt;

&lt;p&gt;The biggest lie is thinking that React Native is akin to coding in ReactJS. It is not and I don't think the name "React" should even be used in "React Native". I'll go as far as to provide this analogy: &lt;em&gt;"Javascript is to Java"&lt;/em&gt; as &lt;em&gt;"ReactJS is to React Native"&lt;/em&gt;. &lt;br&gt;
That's my opinion so don't be offended. There are actually a few shared concepts between React Native such as page routing, import statements, and function logic.&lt;/p&gt;
&lt;h2&gt;
  
  
  Building Steps
&lt;/h2&gt;

&lt;p&gt;In the following process, you'll learn to:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Install React Expo SDK 53&lt;/li&gt;
&lt;li&gt;Start a project&lt;/li&gt;
&lt;li&gt;Debug/Test with the Expo emulator&lt;/li&gt;
&lt;li&gt;Deploy app with EAS&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;What do we want to accomplish? A mobile app but a really basic app for learning purposes. So does it matter if the app loads content from the internet or the phone itself? The early app-generator frameworks were just placing wrappers around GUIs, websites and other elements; essentially websites wrapped by mobile apps. This is what we are going to do giving you exposure to React Expo so you can get a taste of it without dedicating time to build a full-fledged React Native app.&lt;/p&gt;

&lt;p&gt;Afterwards, I'll show you the commands to test your app locally (real-time previews), on your phone and generate the necessary files to do a real installation of the app. Without React Expo, you would have to install Android Studio which is ~7gb in size and compile or build code to see each change. This is unlike web development which has a smoother workflow.&lt;/p&gt;

&lt;p&gt;Here are 2 amazing parts that speed up making a mobile app unlike any other:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;npx create-expo-app myNewApp&lt;/code&gt; creates your app boilerplate&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;eas build --platform all&lt;/code&gt; builds your app file for deployment to the app store &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now for the quickstart guide to create a mobile app based of a website. We're going to use the webview method to render our website inside the React Native code. This is in no way the best method to build an app; I am simply demonstrating the conveniences and speed of the process using React Expo.&lt;/p&gt;

&lt;p&gt;Ensure you have NodeJS installed including &lt;code&gt;npm &amp;amp; npx&lt;/code&gt; so you can run the appropriate commands. &lt;a href="https://nodejs.org/en/download" rel="noopener noreferrer"&gt;Download NodeJS here&lt;/a&gt; and then install npx with the global flag:&lt;br&gt;
&lt;code&gt;npm install -g npx&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now install the boilerplate code provided by Expo:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx create-expo-app myNewApp
cd myNewApp
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;cd myNewApp&lt;/code&gt; and see the project folders and files:&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%2Fgyg69opv7thxicnbo4uu.jpg" 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%2Fgyg69opv7thxicnbo4uu.jpg" alt="Boilerplate react expo folder structure" width="800" height="585"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Next, install the webview component by command line. This is how 95% of adding parts to your app looks like.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx expo install react-native-webview
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Navigate to your &lt;code&gt;webview/app/(tabs)&lt;/code&gt; folder and delete &lt;code&gt;explore.tsx&lt;/code&gt; and replace the contents of &lt;code&gt;index.tsx&lt;/code&gt;. We won't use those.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { WebView } from 'react-native-webview';
import { StyleSheet } from 'react-native';

export default function App() {
  return (
    &amp;lt;WebView
      style={styles.container}
      source={{ uri: 'https://expo.dev' }}
    /&amp;gt;
  );
}
// Styling
const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 20,
  },
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After you replaced the &lt;code&gt;index.tsx&lt;/code&gt; file you can preview your project in the browser and android phone by the command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx expo start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&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%2Fa6wpddu1ecz2dmil6b1n.jpg" 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%2Fa6wpddu1ecz2dmil6b1n.jpg" alt="Expo start commands" width="800" height="749"&gt;&lt;/a&gt;&lt;br&gt;
This screen shows the benefits of running one React Expo command which doubles as your local web server, allows you to open Android Studio, iOS simulator, reload the app, etc.&lt;/p&gt;

&lt;p&gt;Type "w" and your browser will open with an error.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;React Native WebView does not support this platform.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This occurs because, ironically, the webview feature does not load the website from your code as shown &lt;code&gt;source={{ uri: 'https://expo.dev' }}&lt;/code&gt; because it's not Android. So the next step is to preview the app on your android with "Expo Go" instead of Android Studio. &lt;a href="https://play.google.com/store/apps/details?id=host.exp.exponent" rel="noopener noreferrer"&gt;Download Expo Go&lt;/a&gt; from the Google Play Store.&lt;/p&gt;

&lt;p&gt;Then connect WIFI on your phone to the same network as your computer. This is what the Expo Go app looks like.&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%2Fqf6cms4bzp12s9wqouah.webp" 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%2Fqf6cms4bzp12s9wqouah.webp" alt="Expo Go App" width="800" height="1644"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Scan the QR code with your phone, make sure internet is available and your app should render the website &lt;a href="https://expo.dev" rel="noopener noreferrer"&gt;https://expo.dev&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If you're satisfied with your app, then build it and submit it to the app store. Ensure you have an account on Expo, there's a free plan available.&lt;/p&gt;

&lt;p&gt;Use the command below and Expo.dev will generate the build files for you:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;eas build --platform all
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>reactnative</category>
      <category>reactexpo</category>
      <category>mobile</category>
      <category>android</category>
    </item>
    <item>
      <title>Build an anti-spam, double opt-in Email form with Python</title>
      <dc:creator>Rutkat</dc:creator>
      <pubDate>Wed, 14 Aug 2024 02:57:32 +0000</pubDate>
      <link>https://dev.to/rutkat/build-an-anti-spam-opt-in-email-registration-with-python-1034</link>
      <guid>https://dev.to/rutkat/build-an-anti-spam-opt-in-email-registration-with-python-1034</guid>
      <description>&lt;h2&gt;
  
  
  So you want to build an app and get many users?
&lt;/h2&gt;

&lt;p&gt;We all do and if you're a beginner you need to take the following email sign-up features into consideration. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Filtering input for a valid email address&lt;/li&gt;
&lt;li&gt;Double opt-in sign-up&lt;/li&gt;
&lt;li&gt;Bot/spam prevention&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A solid email sign-up form is essential for web apps, newsletters, freebie downloads, invites to private groups, and lead generation. It allows you to collect valid email address and establish personal communication without relying on social media or other platforms. Do respect the email data and abide your region's anti-spam regulations such as the can-spam act.&lt;/p&gt;

&lt;p&gt;Let's not rely on using 3rd party services such as Auth0, Facebook, or Google to have access to your app and services which can shut your down at any given time. &lt;strong&gt;Keep your app data yours!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Starting off, you should have some experience in &lt;strong&gt;Python because we're going to use the Flask framework with a MySQL database&lt;/strong&gt;. This is going to be more fun (maybe) than using Wordpress, the most popular CMS. You would have to pay for some Wordpress plugin to have the same capability as a free Flask extension. I've build previously built on Wordpress (PHP) and prefer Python Flask for web apps even though Wordpress is very capable of making web apps.&lt;/p&gt;

&lt;p&gt;We're going to use existing Python modules which simplify cleaning user input,  generating a verification link, and communicating with the database.&lt;/p&gt;

&lt;p&gt;Each code snippet will be explained and include some comments in the code. In case you haven't build user-registration or know of the inner workings, I will describe the details for you and then you can see the final code at the end (don't skip ahead). &lt;/p&gt;

&lt;p&gt;Here is a summary of the features we will implement as stated in the first paragraph:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;A valid email address&lt;/strong&gt; can be checked by parsing the input string from the user using a regular expression or a Flask extension. We won't allow random text nor SQL injection type of hacks. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;strong&gt;double opt-in method&lt;/strong&gt; requires the recipient to give permission for you to email them by receiving a validation link to their inbox. This is mainly used to prevent someone else from using your email address. This also prevents test users who just sign-up and abandon their accounts.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Bot prevention&lt;/strong&gt; can be done with a hidden field that is not shown to the user but is commonly auto-filled by bots crawling for vulnerable sign-up forms but it is not as reliable is a "captcha" from a 3rd party service.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's code it out!&lt;/p&gt;

&lt;p&gt;Create a working directory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir signup
cd signup
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create your Python environment using &lt;code&gt;python3 -m venv signup&lt;/code&gt; or &lt;code&gt;conda create -n double-opt-contact python3&lt;/code&gt;. I prefer conda and if you want to learn more you can read my Python environments article.&lt;/p&gt;

&lt;p&gt;Install the following dependencies:&lt;br&gt;
&lt;code&gt;pip flask flask-mail secure SQLAlchemy Flask-WTF Flask-SQLAlchemy mysql-connector-python bleach&lt;br&gt;
&lt;/code&gt;&lt;br&gt;
Alternatively, you can have the same dependencies listed in a &lt;code&gt;requirements.txt&lt;/code&gt; file and run &lt;code&gt;pip install -r requirements.txt&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Create &lt;code&gt;app.py&lt;/code&gt; file with the following dependencies included:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask import Flask, render_template, request, url_for, redirect, flash
from flask_mail import Mail, Message
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import func
from itsdangerous import URLSafeTimedSerializer, SignatureExpired
import secrets
import bleach
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Initialize the app object with default template folder location:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app = Flask(__name__, template_folder='templates')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Enter your own server configuration data using these lines:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Flask configurations
secret = secrets.token_urlsafe(32)
app.secret_key = secret
app.config['SECRET_KEY'] = secret # auto-generated secret key

# SQLAlchemy configurations
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://admin:user@localhost/tablename'

# Email configurations
app.config['MAIL_SERVER'] = 'smtp.example.com'
app.config['MAIL_PORT'] = 465 #check your port
app.config['MAIL_USERNAME'] = 'your_email@example.com'
app.config['MAIL_PASSWORD'] = 'your_password'
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False

db = SQLAlchemy(app)
mail = Mail(app)
sserialzer = URLSafeTimedSerializer(app.config['SECRET_KEY']) #set secret to the serliazer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Ultimately, you should have your config info in a &lt;code&gt;.env&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;We will need a MySQL database to store users which can be created manually or by Python code. As part of the learning process, you can enter the following code using the command-line or using Python's &lt;code&gt;with app.app_context() db_create_all()&lt;/code&gt; method.  &lt;/p&gt;

&lt;p&gt;The validated field is for a token string which allows the double opt-in technique.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(120) NOT NULL UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    validated BOOLEAN DEFAULT FALSE
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The next section uses SQLAlchemy's ORM structure to query the database for you. Take note that &lt;strong&gt;the class name should match your database table name&lt;/strong&gt; otherwise you'll get an error. The &lt;code&gt;db.model&lt;/code&gt; represents your table settings which include the column name, it's type, length, key and null value:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True, nullable=False)
    created_at = db.Column(db.DateTime, server_default=db.func.now())
    validated = db.Column(db.Boolean, default=False)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you haven't manually created the MySQL database table already, you can do it with this Flask code directly after the &lt;code&gt;class User&lt;/code&gt; code block:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Create the database table
with app.app_context():
    db.create_all()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For brevity of this tutorial, we're skipping the index page or what you would want to call your app homepage and just show the sign-up page using Python's decorator function for the page route, but first we need an html template for the front end to render. The braces &lt;code&gt;{}&lt;/code&gt; allow for python code inside the html:&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;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
    &amp;lt;title&amp;gt;Email Sign Up&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;h1&amp;gt;Sign Up&amp;lt;/h1&amp;gt;
    &amp;lt;form action="{{ url_for('signup') }}" method="POST"&amp;gt;
        &amp;lt;input type="email" name="email" placeholder="Enter your email" required&amp;gt;
        &amp;lt;input type="submit" value="Sign Up"&amp;gt;
    &amp;lt;/form&amp;gt;
    {% with messages = get_flashed_messages(with_categories=true) %}
      {% if messages %}
        &amp;lt;ul&amp;gt;
          {% for category, message in messages %}
            &amp;lt;li&amp;gt;{{ message }}&amp;lt;/li&amp;gt;
          {% endfor %}
        &amp;lt;/ul&amp;gt;
      {% endif %}
    {% endwith %}
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we enter the back-end code which are 2 pages/routes (index,  signup), the email message, and confirmation. The signup page includes the &lt;code&gt;GET/POST&lt;/code&gt; methods which allow the form to be submitted. The &lt;code&gt;bleach&lt;/code&gt; object is Python extension that cleans the input from the user to ensure security and mitigating malicious scripts. Then the &lt;code&gt;sserializer&lt;/code&gt; generates a one-time token to email the verification link.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route('/')
def index():
    return '&amp;lt;h1&amp;gt;Index page&amp;lt;/h1&amp;gt;'

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    if request.method == 'POST':
        email = bleach.clean(request.form.get('email'))

        # Insert user into the database
        new_user = User(email=email)
        try:
            db.session.add(new_user)
            db.session.commit()
        except Exception as e:
            print(f"Error occurred saving to db: {e}")

        # Send confirmation email
        token = sserialzer.dumps(email, salt='email-confirm')
        msg = Message('Confirm your Email', sender='your_email@example.com', recipients=[email])
        link = url_for('confirm_email', token=token, _external=True)
        msg.body = f'Your link is {link}'
        try:
            mail.send(msg)
        except Exception as e:
            print(f"Error occurred sending message: {e}")
            flash("Error occurred sending message!")
            return render_template('signup.html')  
        flash('A confirmation email has been sent to your email address.', 'success')
        return redirect(url_for('index'))
    return render_template('signup.html')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before adding the html sign-up form, let's complete the backend by adding the route for validating the double opt-in feature. This route uses the &lt;code&gt;s&lt;/code&gt; variable we created earlier which generates the time-sensitive, secret token. See &lt;a href="https://itsdangerous.palletsprojects.com/en/2.1.x/url_safe/" rel="noopener noreferrer"&gt;the docs for details&lt;/a&gt;&lt;br&gt;
The max age is the seconds before the link expires so in this case, the user has 20 minutes to confirm their email address.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route('/confirm_email/&amp;lt;token&amp;gt;')
def confirm_email(token):
    try:
        email = sserialzer.loads(token, salt='email-confirm', max_age=1200)  # Token expires after 1 hour
    except SignatureExpired:
        return '&amp;lt;h1&amp;gt;The token is expired!&amp;lt;/h1&amp;gt;'

    # Update field in database
    user = User.query.filter_by(email=email).first_or_404()
    user.validated = True
    db.session.commit()

    return '&amp;lt;h1&amp;gt;Email address confirmed!&amp;lt;/h1&amp;gt;'

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now for the ubiquitous main statement which tells Python to execute the script if the file is being executed directly (as opposed to an imported module):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if __name__ == '__main__':
    app.run()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Your code should be working from this point when you run the flask command with debugging enabled. This will allow you to see any errors in the command line as well as the browser window:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;flask --app app.py --debug run 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Open your browser to the domain shown in the command-line (localhost) and the index page should render. Try to submit the form using a valid email address to receive the verification link. Once you get the link which should look like &lt;code&gt;http://localhost:5000/confirm_email/InRvbUByYXRldG91cmd1aWRlcy5jb20i.ZteEvQ.7o1_L0uM9Wl8uii7KhJdiWAH&lt;/code&gt;, you can follow it and get the email address validated using the validator route shown here:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@app.route('/confirm_email/&amp;lt;token&amp;gt;')
def confirm_email(token):
    try:
        email = sserializer.loads(token, salt='email-confirm', max_age=1200)  # Token expires after 1 hour
    except SignatureExpired:
        return '&amp;lt;h1&amp;gt;Oops, the token expired!&amp;lt;/h1&amp;gt;'

    # Update field in database
    user = Users.query.filter_by(email=email).first_or_404()
    user.validated = True
    try:
        db.session.commit()
    except Exception as e:
        print(f"Error occurred saving to db: {e}")

    return '&amp;lt;h1&amp;gt;Email address confirmed!&amp;lt;/h1&amp;gt;'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This route accepts the token string previously sent to you and checks it to see if it matches the corresponding database entry. If it does, it updates the &lt;code&gt;validated&lt;/code&gt; field to &lt;code&gt;True&lt;/code&gt; and you can rest knowing your sign-up form wasn't abandoned. &lt;/p&gt;

&lt;p&gt;This is an important step all successful businesses use in their registration systems and now you have it to. But wait, what if we get bots attacks submitting random email addresses without validating them. Then you will have a dirty database filled with useless entries. Let's prevent that!&lt;/p&gt;

&lt;p&gt;To prevent bot attacks or at least mitigate the advanced once you can build your own time-consuming solution, include a IP limiter which requires an in-memory database such as redis or you can use a 3rd party service such as Google's captcha or hCaptcha. &lt;/p&gt;

&lt;p&gt;In our tutorial, we will add &lt;a href="https://www.hcaptcha.com/plans" rel="noopener noreferrer"&gt;hcaptcha's free plan&lt;/a&gt;. At the time of this writing, google's captcha isn't free and hcaptcha is. To have this functioning for your site, you need to register with them to get API key from hcaptcha.&lt;/p&gt;

&lt;p&gt;We need new requirements so install them:&lt;br&gt;
&lt;code&gt;pip install flask-hcaptcha requests&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Requests is needed to send the email address to hcaptcha for validation. Get the key and integrate hcaptcha's javascript file with your html signup form. Add the file to the head of your html page and your site key to your form:&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;head&amp;gt;
   ...
   &amp;lt;script src="https://hcaptcha.com/1/api.js" async defer&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
   ...
   &amp;lt;form action="{{ url_for('signup') }}" method="POST"&amp;gt;
       &amp;lt;input type="email" name="email" placeholder="Enter your email" required&amp;gt;
       &amp;lt;input type="submit" value="Sign Up"&amp;gt;
       &amp;lt;div class="h-captcha" data-sitekey="b62gbcc-5cg2-41b2-cd5a-de95dd1eg61h" data-size="compact"&amp;gt;&amp;lt;/div&amp;gt;
   &amp;lt;/form&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The site key in this code is an example, you will need your own from the free plan. This site key validates your form and inspects the site visitor with a comprehensive list of spam bots known by hcaptcha.&lt;/p&gt;

&lt;p&gt;Next modify your &lt;code&gt;app.py&lt;/code&gt; file to include the hcaptcha's secret key (not the site key) in the app.config object and post the response to hcaptcha prior to saving to your own database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  app.config['HCAPTCHA_SECRET_KEY'] = 'your-secret-hcaptcha-key'
  ...
@app.route("/signup", methods=['GET', 'POST'])
def signup():
    if request.method == 'POST':
        email = bleach.clean(request.form.get('email'))
        hcaptcha_response = request.form.get('h-captcha-response')
        # Verify hCaptcha response
        payload = {
            'secret': app.config['HCAPTCHA_SECRET_KEY'],
            'response': hcaptcha_response
        }
        try:
            response = requests.post('https://hcaptcha.com/siteverify', data=payload, timeout=10)
            result = response.json()
        except requests.exceptions.RequestException as e:
            print(f"Request failed: {e}")

        if not result.get('success'):
            flash('CAPTCHA validation failed, please try again.', 'danger')
         ...
        # Insert user into the database
        new_user = Users(email=email)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once this is done, you will have the hcaptcha icon showing in your sign-up form and it should be enabled preventing any spam. Now you have a more robust form for your new app.&lt;/p&gt;

&lt;p&gt;In case you encountered any errors or you have a typo in the code you can check the completed code on &lt;a href="https://github.com/rutkat/python-fullstack/tree/main/double-opt-contact" rel="noopener noreferrer"&gt;my github.com &lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Follow and like for more!&lt;/p&gt;

</description>
      <category>python</category>
      <category>antispam</category>
      <category>webdev</category>
      <category>backend</category>
    </item>
    <item>
      <title>How to manipulate text strings like a boss!</title>
      <dc:creator>Rutkat</dc:creator>
      <pubDate>Fri, 16 Jul 2021 03:15:52 +0000</pubDate>
      <link>https://dev.to/rutkat/how-to-manipulate-text-strings-like-a-boss-1blp</link>
      <guid>https://dev.to/rutkat/how-to-manipulate-text-strings-like-a-boss-1blp</guid>
      <description>&lt;p&gt;Have you wondered how censoring words on the internet occurs? Perhaps you want to know why your username on apps has to conform to specific rules? This is done through string manipulation using code such as &lt;strong&gt;javascript&lt;/strong&gt; among many others. &lt;/p&gt;

&lt;p&gt;A &lt;em&gt;string&lt;/em&gt; is just a specific name used to label a piece of data which contains text and can consist of alpha-numeric characters mixed with numbers and symbols. &lt;em&gt;Why is the important?&lt;/em&gt; Every software application with a presentation layer applies a form of string manipulation and it is the foundation to algorithms. Think how it applies to business ideas as well. Grammarly is an excellent example of a business that is all about string manipulation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;By the end of this article, you will have the ability to understand how text manipulation works.&lt;/strong&gt; I will explain the ins and outs of string manipulation so you can think how code processes it. &lt;em&gt;Don't worry,&lt;/em&gt; we won't discuss the bits and bytes of strings but rather the ways you can manipulate strings and how it is done. Also, I will use the terms string and text interchangeably without getting scientific. Remember that a practical example or analogy will help you memorize the specific ways needed to manipulate strings.&lt;/p&gt;

&lt;h2&gt;
  
  
  TEXT AND STRINGS
&lt;/h2&gt;

&lt;p&gt;First thing to consider is how to engage text manipulation from a visual perspective. For example, if you're a non-coder or just a human being, you know you can write text on paper, on your smartphone, computer, and even rice. Okay maybe not rice. The writing can occur from left-to-right, top-to-bottom, right-handed, left-handed, etc. Afterwards, you can manipulate what you wrote with an eraser, scratching it out, or tapping the backspace key.&lt;/p&gt;

&lt;p&gt;From a coder's perspective, it doesn't work the same way, except when writing the actual code. The code instructions for manipulating strings have restrictions and specific methods. You will learn these methods here but let's start with more of a visual approach to envision how code will do the magical transformations.&lt;/p&gt;

&lt;h2&gt;
  
  
  WHICH DIRECTION
&lt;/h2&gt;

&lt;p&gt;Like writing, strings can be manipulated from left-to-right and right-to-left. The length of a string can be as little as a single space to pages of text, but most commonly in code, a string will not be longer than a sentence. A string can be a username, phone number, a snippet of code, a poem etc. &lt;/p&gt;

&lt;p&gt;When working with a specific coding language, there are built-in methods to use or you can create your own custom method. A combination of these methods can manipulate text to do virtually whatever you want. &lt;em&gt;You can become a string master with the force of practice.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Besides processing a string from left-to-right or right-to-left, it can be broken down and manipulated to individual characters using the number representing the position of any character. This is known as the index value of the string. For example, the string "Hello!" contains 6 characters, so your code can directly access any letter by indicating a corresponding index number.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"Hello!"
 123456 (number represents position)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  TRAVERSING
&lt;/h2&gt;

&lt;p&gt;Several coding methods will process the string in this ascending-numerical order however since computers compute with a basis of zero, the first item position is &lt;strong&gt;always 0&lt;/strong&gt;. To be more accurate, I should state that the computer is traversing, not processing strings. The difference is that "processing" indicates an effect happens whereas "traversing" indicates a passage or travel across something. &lt;/p&gt;

&lt;p&gt;When dealing with code instructions, you should be conscious about the computing resources utilized so you may not need to process every character in a string but rather traverse to the individual character you need to change. &lt;/p&gt;

&lt;p&gt;For example, your objective is to remove punctuation so you have several approaches to remove the "!" From "Hello!". You can use a method to find the position of "!" or you can access the last character of the string. These methods include getting the length of the string, getting the index of "!" or traversing the string in reverse. &lt;/p&gt;

&lt;p&gt;If use the length method, you have to remember to subtract 1 since computing starts with zero. Also spaces count as part of the string and will have an index position thus increasing the length of the string.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The INDEX number represents the position of a character in a string.&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"Hello!"
 012345 character positions

"Hello!".length - 1
Length is a property of a string.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here are methods to get the position of a character in a string:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"Hello!".indexOf("!")
Find the first position of a character searching from left-to-right.

"Hello!".lastIndexOf("!") 
Find the last position of a character searching from right-to-left.

"Hello!".length - 1
Find the last character in a string.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All give &lt;code&gt;5&lt;/code&gt; as the result. You can do the opposite with the &lt;code&gt;charAt()&lt;/code&gt; method which returns the character from a string specified by the position.&lt;/p&gt;

&lt;p&gt;"Hello!".charAt(5)&lt;br&gt;
Result is "!"&lt;/p&gt;
&lt;h2&gt;
  
  
  ONE CHARACTER
&lt;/h2&gt;

&lt;p&gt;Now you know the basics of traversing a string one character at a time, which are from the left, from the right, and from the end using index numbers. However, not all methods return the position of the character you seek. You may prefer a result as a boolean data type instead. Meaning your search is a test which returns true or false.&lt;/p&gt;

&lt;p&gt;Boolean test methods: includes, startsWith, endsWith&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"Hello!".includes("!")
True

"Hello!".startsWidth("!")
False

"Hello!".endsWith("!")
True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These character checks are not as useful as finding the position of a character, because you cannot proceed with your algorithm if your purpose is to modify the string with the same search query. Besides there are more powerful methods for true/false checks which we will be described later. Up to this point we have learned to traverse a string left-to-right and right-to-left so what's the next step? Modification!&lt;/p&gt;

&lt;p&gt;We can us several built-in methods or create our own for changing the text in a string. Let's start with the methods which don't require indicating a search query or index position. Since humans care more about uppercase and lowercase letters than computers, we can instantly transform an entire string use these two methods:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"Hello!".toUpperCase()
Result "HELLO!"

"Hello!".toLowerCase()
Result "hello!"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you have seen a camel then you know they have humps and in programming when code &lt;code&gt;LooksLikeThis&lt;/code&gt; it is called camel case. This is because it has humps and no spaces. You will have to traverse and recognize this type some day. We do this to make text easier to read for humans because who likes to read &lt;code&gt;"a sEnTEnCe liKE ThiS!?"&lt;/code&gt; Actually, this method is also useful for web apps like blogs which take an article title and create a url known as a slug.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
Article name &lt;code&gt;"Mastering String Manipulation"&lt;/code&gt;&lt;br&gt;
Slug url &lt;code&gt;"domain.com/mastering-string-manipulation/"&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Since there are multiple methods to get the same result, Let's begin with this example of combining strings into one. This is known as concatenation. You can use the "+" symbol or the concat method. Please note that since Javascript does not automatically enforce data types, so you should ensure that the data types are strings as opposed to arrays or booleans when using "+". This topic is for another entire article. With the lack of data type enforcement, erroneous output can occur as a result of type coercion. Meaning the + sign can accidentally change an integer to a string.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"Hello" + "World"
Result "HelloWorld"

"Hello".concat("World")
Result "HelloWorld"

"12" + 12
Result "1212", not 24.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The newest way to concatenate strings is using template strings which utilize the back-tick symbol and curly braces {} after the $ symbol. Yes, using those three symbols is required. You will see this in emails as well as websites to customize the writing output based on the user's information.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var myString = "Hello"
Var string2 = "World"
`${myString} ${World}`
Result "Hello World"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Previously I stated that empty spaces count towards the length of a string, in other words they occupy a space in a string and can be manipulated as well. Since we want to be efficient in saving data as well as making text easy to read, we want to prevent unnecessary blank space and this can be done with the trim method. &lt;/p&gt;

&lt;p&gt;It removes empty spaces at the beginning and end of a string, but not in the middle. If you want to remove empty space in the middle of a string, you have to utilize a more powerful method know as a &lt;strong&gt;"regular expression"&lt;/strong&gt; which will be described later.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;`" Hello World. ".trim()`
Result "Hello World."
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To do the opposite, there is a method for that. You can pad a string at the end or beginning with any character. Let's say your web app deals with sensitive information like credit cards or you have ID numbers which have to conform to a specific length. You can use the &lt;code&gt;padStart&lt;/code&gt; and &lt;code&gt;padEnd&lt;/code&gt; methods for this. For example, a credit card number is saved in the app but you only want to show the last four digits prefixed with the * symbol.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"4444".padStart(8, "*")
Result "********4444"

"1234".padStart(4, "0")
Result "00001234"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Besides concatenating strings, you can also repeat them with a multiplier. It's uncommon to repeat text so the method will be more useful for symbols such as periods. For example, when you need to truncate a string and indicate to the reader that the string continues, you can use ellipses like this... It could also be useful for songs where lyrics are repeated. Actually, it's rare to see this method in code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"Hello-".repeat(3)
Result "Hello-Hello-Hello"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  PIZZA SLICE
&lt;/h2&gt;

&lt;p&gt;Let's expand our character searches!&lt;br&gt;
Using the previous search methods we are only able to retrieve one character at a time from a string. What if we want to select a word or a section of a string using an index range. Well we can do that by slicing a pizza and eating the slice we want. Almost! &lt;/p&gt;

&lt;p&gt;The string method is called slice so a pizza slice is a good metaphor. For this, you have to pass in the start and end positions of your search query. The start position can be a negative number which will traverse the string in reverse or from the end of it. You may think, wouldn't it be easier to just match a word inside a string? &lt;/p&gt;

&lt;p&gt;Well yes, but in some cases, coders may not be able to predict what strings they will encountered or the string will be a pre-determined length.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"Hello World".slice(6)
Result "World"

"Hello World".slice(6, 8)
Result "Wo"

"Hello World".slice(-3)
Result "rld"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Up to this point you have learned to traverse strings from the left and from the right, get character positions, do boolean tests, transform character cases, concatenate strings, remove empty space, pad, repeat strings and extract sub-strings. How about we learn how to revise our strings with the replace method. Scenarios for this can be removing explicit words, swapping first name with last name, swapping "-" for empty space " ". &lt;/p&gt;

&lt;p&gt;The difference with the &lt;code&gt;replace&lt;/code&gt; method compared to the previous methods in this article is that replace accepts strings and regular expressions as search queries. It also accepts a function as a second parameter but we won't go into custom functions at this time. With replace, you don't need to rely on using index positions but you need to be familiar with regular expressions (regexp  or regex for short) because it is how you can replace multiple instances of the search query. Note the usage of a regular expression with the forward slashes surround the search term.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"Very bad word".replace("bad", "good")
Result "Very good word"

"Very bad bad word".replace("bad", "good")
Result "Very good bad word"

"Very bad bad word".replace("bad", "good")

"Very bad bad word".replace(/bad/, "good")
Result "Very good bad word"

"Very bad bad word".replace(/bad/g, "good")
Result "Very good good word"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  CRYPTIC PATTERNS
&lt;/h2&gt;

&lt;p&gt;Are you beginning to feel the power of string manipulation? You are slowly becoming an expert. A regexp can be denoted using the forward slash / outside of the search word and the letter g after the second slash / indicates a global search which will replace multiple instances of the word inside the string. Generally, it's better to use &lt;code&gt;indexOf()&lt;/code&gt; and &lt;code&gt;replace()&lt;/code&gt; for faster function execution speed and when searching for one instance of a word.&lt;/p&gt;

&lt;p&gt;Otherwise, to understand regular expressions you have to memorize the symbols on your keyboard. Many symbols including letter cases. In fact, there's nothing regular about "regular expressions". It should be called "cryptic patterns" because no human being can read them without finding the meaning of the symbols used. To simplify the meaning for human language consumption, you can also say they are string-searching algorithms.&lt;/p&gt;

&lt;h2&gt;
  
  
  MAGIC WAND
&lt;/h2&gt;

&lt;p&gt;Before I show you some of the characters used, I would like to paint you a picture of the traversing that happens using regexp. First imagine a magic wand in your hand. Waving the magic wand releases magical stars onto the string which modify it to the desired string you want. Each star represents a symbol in the regular expression and that is what you have to come up with as a search pattern. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Regular expressions are truly powerful search techniques&lt;/em&gt;. You can find a needle in a haystack instantly, well more like in micro-seconds. Many input forms on the web use regular expressions to conform text into specific formats such as zip codes, phone numbers, domain names, currency values and the list can goes on. Do note that there are different regular expression engines depending on the programming language and the following is specific to javascript.&lt;/p&gt;

&lt;p&gt;We can get more specific and describe those symbols and their purpose. To try out regular expressions yourself you can visit a website such as &lt;a href="https://regexr.com/" rel="noopener noreferrer"&gt;https://regexr.com/&lt;/a&gt;&lt;br&gt;
Practice on this website by copying and pasting examples from this article or invent your own patterns.&lt;/p&gt;

&lt;p&gt;/term/ regexp always has to be contained inside two forward slashes. "A/B/C" is not a regexp. Every character or symbol between the slashes represents something other than the symbol itself.&lt;/p&gt;

&lt;p&gt;/abc/ any alphabetical character without symbols is equivalent to a regular consecutive search string.&lt;/p&gt;

&lt;p&gt;/\$/ An explicit search for a symbol has to be prefixed with a backward slash \, in this case it's the dollar symbol. It's called escaping even though none of them will run away. The symbols still need to escape from the wrath of your cryptic search desires.&lt;/p&gt;

&lt;p&gt;/^abc/ and /abc$/ These symbols don't have to be escaped. They are the carrot &lt;code&gt;^&lt;/code&gt; and dollar sign &lt;code&gt;$&lt;/code&gt;. Their purpose is to restrict the search to the beginning and ending of a string respectively. This is also known as anchoring so they can be called anchors. In this case, it means if "abc" is in the middle of "xyzabczyx", it will be ignored. &lt;code&gt;^&lt;/code&gt; means the string must start with "abc" and &lt;code&gt;$&lt;/code&gt; means that the string must end with "abc". You can apply one or both.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;What if you don't want to search for an alphabetical character nor a symbol, but a formatting change in the string.&lt;/em&gt; Since I mentioned an empty space has meaning in code, so does, a tab, a new line, and a carriage return. These can be searched using a combination of backslash and one letter. For brevity, we've excluded the surrounding slashes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;\n Find a newline
\t Find a tab
\r Find a carriage return
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;This is mind-blowing right?&lt;/strong&gt; You can manipulate empty space and look for invisible metacharacters which control formatting using regexp. Let's try a regexp example based on what we know so far. We want a specific dollar amount in the beginning of a string $10.xx and any cent amount.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/^\$10\.\d\d/ 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are using ^ to match the start&lt;br&gt;
then a backslash \ to escape the dollar $ sign&lt;br&gt;
the number 10 followed by an escaped period .&lt;br&gt;
the escaped \d represents any digit 0-9 so we have it twice&lt;/p&gt;

&lt;p&gt;As previously mentioned, adding a backslash to any letter changes the search pattern. Here are some search patters with the backlash and letter combination.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;\w Matches any word
\d Matches any digit
\s Matches empty space
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In addition to that you can match the negation or the opposite with the capital letter equivalents.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;\W don't match a word
\D don't match a digit
\S don't match empty space
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  GLOBALLY INSENSITIVE
&lt;/h2&gt;

&lt;p&gt;Now that you are getting more comfortable with the possibilities of regular expressions, you need to be aware of the letters "g" and "i" at the ending of the regexp term, right after the second forward slash. These are known as flags which modify your search. The "g" means global so it will return more than one result match if available while the "i" means insensitive in regards to text case. Uppercase or lowercase will not matter using this flag.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/term/g Finds multiple instances, not just the first
/term/i Finds uppercase and lowercase characters
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To expand on your searches, here's the next addition of complexity. You may want to find a combination of letters, numbers or symbols. You can do this by grouping inside parentheses () and brackets []. The brackets are specific to character ranges such as 0-9 or A-Z uppercase, a-z lowercase. You can use multiple dashes for multiple ranges inside a single set of brackets. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Parentheses are not useful alone&lt;/em&gt;, but when you have additional search terms in one regexp. To throw in a monkey wrench, the carrot ^ symbol inside a bracket set will negate the search.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/[abc]/ Matches any of the letter a, b, or c.
/[0-7]/ Matches numbers 0-7 anywhere in the string.
/[^0-7]/ Don't match numbers 0-7 anywhere in the string.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;[0-9] is identical to the \d for digits while \w is identical for [a-z] words. &lt;/p&gt;

&lt;p&gt;Using parentheses () is useful when you want to search more than one pattern such as international phone numbers while brackets [] or for searching sets. When using parentheses in your search, you may also include the pipe symbol | as an OR operator. This means your result can be the search pattern on either side of the pipe. This is known as alternation. Here are examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/[abc](123)/ Matches a, b, or c, followed by 123
/gr[ae]y/ Matches gray or grey
/(gray|grey)/ Matches gray or grey
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  QUANTIFIERS
&lt;/h2&gt;

&lt;p&gt;Do you want to match a specific amount of letters or numbers? Perhaps 0 or 1, 1 or many, only 4. It's all possible with quantifiers. Here's are quantifier symbols and how you can use them. We will use the letter "a" as part of the example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/a*/ Matches 0 or more letter a
/a+/ Matches 1 or more letter a
/a?/ Matches 0 or 1 letter a
/a{4}/ Matches exactly 4 consecutive letters a.
/a{2,3}/ Matches between 2-3 letters a.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The possibilities don't stop here. This is why algorithms utilize regular expressions regularly so becoming an export in them is going to take you a long way. In total, there are 11 metacharacters available for regular expressions. They are: \ ^ $ . | ? * + () [] {} Each has a purpose.&lt;/p&gt;

&lt;p&gt;Another practical example is to find html tags because they are the foundation of websites. Let's think this through before typing out the expression. 1. We need at least one letter because all tags start with a letter and while it should be lowercase, we may encounter legacy html that is capitalized. &lt;/p&gt;

&lt;p&gt;Next, we shall expect more letters or a number such as h1 tags. While the * will get one or more characters, we can limit the amount using {} instead. The following will capture html tags without attributes:&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;[A-Za-z][A-Za-z0-9]*&amp;gt;/g Matches html tags
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  LOOK AROUND
&lt;/h2&gt;

&lt;p&gt;Finally, there is another advanced concept if regular expressions weren't advanced enough. It is called the lookahead. There's a positive and negative lookahead. It must be placed inside parentheses and begin with a question mark ?. Essentially a lookahead matches the search pattern but does not capture it or you can think of it as to match something not followed by something else. This is useful when doing a combined search pattern by grouping. To demonstrate, let's search for a dollar value in a string that is followed by "USD" but we don't want to capture the "USD". We will use the positive lookahead using &lt;code&gt;(?=&lt;/code&gt; and the negative lookahead using &lt;code&gt;(?!&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;/\$30(?=USD)/ Matches $30 from "The product costs $30USD"
/\$30(?!USD)/ Matches $30 from "The USD value is $30"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  SUMMARY
&lt;/h2&gt;

&lt;p&gt;There we have it! &lt;em&gt;A comprehensive usage of javascript for manipulating strings to your desires featuring built-in methods and powerful regular expressions.&lt;/em&gt; Now you may approach your coding algorithms easier using all these methods learned and create your own search patterns which can be greedy, fuzzy, lazy, dirty, empty, crazy, etc. This is just the beginning of your algorithm adventures and wielding a superpower called coding.&lt;/p&gt;

&lt;p&gt;I hope you will familiarize yourself with all the methods available and try to memorize them through practice, practice, and more practice.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
