Categories
JavaScript Answers

How to Check Whether a String Contains a Substring in JavaScript?

Checking whether a string has another substring is a common operation we do in JavaScript programs.

In this article, we’ll look at how to check whether a string has another substring in JavaScript.

String.prototype.includes

We can use the includes method that comes with string instances to check whether a string has a substring in JavaScript.

For instance, we can write:

const string = "foo";
const substring = "o";
console.log(string.includes(substring));

It returns true is the substring is in the string and false otherwise.

So this should return true .

We can also pass in a second argument with the index to start searching from.

So we can write:

console.log(str.includes('to be', 1))

to start searching str from index 1.

It’s included with ES6.

If we’re running a JavaScript program in an environment that doesn’t include ES6, we can add the following polyfill:

if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';

    if (search instanceof RegExp) {
      throw TypeError('first argument must not be a RegExp');
    }
    if (start === undefined) { start = 0; }
    return this.indexOf(search, start) !== -1;
  };
}

String.prototype.indexOf

Also, we can use the indexOf to get the first index of the substring in a string.

For instance, we can write:

const string = "foo";
const substring = "o";
console.log(string.indexOf(substring) !== -1);

If indexOf returns -1, then the substring isn’t in the string .

Otherwise, substring is in string .

Conclusion

We can use the indexOf or includes method to check whether a JavaScript substring is in another string.

Categories
JavaScript Answers

How to Redirect to Another Webpage in JavaScript?

Redirecting to another webpage is a common operation we do in JavaScript programs.

In this article, we’ll look at how to redirect to a given URL with JavaScript.

window.location.replace

One way to redirect to a given URL is to use the window.location.replace method.

For instance, we can write:

window.location.replace('https://yahoo.com')

We just pass in the URL in there.

replace doesn’t keep a record in the session history.

We can omit window since window is the global object:

location.replace('https://yahoo.com')

window.location.href

We can also set the window.location.href property to the URL we want to go to.

For instance, we can write:

window.location.href = 'https://yahoo.com'

Setting window.location.href adds a record to the browser history, which is the same as clicking on a link.

Also, we can shorten this to location.href since window is global:

location.href = 'https://yahoo.com'

window.location.assign

Also, we can call window.location.assign to navigate to the URL we want.

For instance, we can write:

window.location.assign('https://yahoo.com')

To navigate to ‘https://yahoo.com' .

It also keeps a record in the browser history.

We can shorten this to location.assign since window is the global object:

location.assign('https://yahoo.com')

Conclusion

There are a few ways to navigate to a URL in our JavaScript app.

Categories
JavaScript Answers

How to Remove a Specific Element from a JavaScript Array?

Removing an item from an array is a common operation we do in JavaScript programs.

In this article, we’ll look at how to remove a specific element from a JavaScript array.

Splice

We can use the array’s splice method to remove an array item with the given index.

For instance, we can write:

const array = [1, 2, 3];
console.log(array);
const index = array.indexOf(2);
if (index > -1) {
  array.splice(index, 1);
}

console.log(array);

We have an array that we want to remove an item from.

We use the indexOf method to find the first index of the given item in the array.

If it returns anything other than -1, then the item is in the array.

And so if index isn’t -1, we call splice with the index and 1 to remove an item with the given index.

This works well with one entry and if we’re looking for a primitive value.

Filter

We can also use the filter method to return the array without the given entry.

For instance, we can write:

const value = 3
let arr = [1, 2, 3, 4, 5]
arr = arr.filter(item => item !== value)
console.log(arr)

We look for value in arr and remove it by calling filter with a callback that returns item !== value .

This will keep anything in arr that has value other than value .

This will remove all entries with the given value so it’s more versatile than using indexOf and splice .

It also works with objects, which makes it more versatile.

indexOf doesn’t work with objects since we can’t specify the condition to look with a callback as we do with filter .

Conclusion

We can remove items with the given condition easily from JavaScript arrays.

Categories
React Projects

Create a Recipe App with React and JavaScript

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a recipe app with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app recipe-app

with NPM to create our React project.

We also need the uuid package to let us generate unique IDs for our recipe items.

To do this, we run:

npm i uuid

Create the Recipe App

To create the recipe app, we write:

import React, { useState } from "react";
import { v4 as uuidv4 } from "uuid";

export default function App() {
  const [recipe, setRecipe] = useState({
    name: "",
    ingredients: "",
    steps: ""
  });
  const [recipes, setRecipes] = useState([]);

  const addRecipe = (e) => {
    e.preventDefault();
    const { name, ingredients, steps } = recipe;
    const formValid = name && ingredients && steps;
    if (!formValid) {
      return;
    }
    setRecipes((recipes) => [
      ...recipes,
      {
        id: uuidv4(),
        ...recipe
      }
    ]);
  };

  const deleteRecipe = (index) => {
    setRecipes((recipes) => recipes.filter((_, i) => i !== index));
  };

  return (
    <div>
      <style>
        {`
        .content {
          white-space: pre-wrap;
        }
        `}
      </style>
      <form onSubmit={addRecipe}>
        <div>
          <label>name</label>
          <input
            value={recipe.name}
            onChange={(e) =>
              setRecipe((recipe) => ({ ...recipe, name: e.target.value }))
            }
          />
        </div>
        <div>
          <label>ingredients</label>
          <input
            value={recipe.ingredients}
            onChange={(e) =>
              setRecipe((recipe) => ({
                ...recipe,
                ingredients: e.target.value
              }))
            }
          />
        </div>
        <div>
          <label>steps</label>
          <textarea
            value={recipe.steps}
            onChange={(e) =>
              setRecipe((recipe) => ({ ...recipe, steps: e.target.value }))
            }
          ></textarea>
        </div>
        <button type="submit">add recipe</button>
      </form>
      {recipes.map((r, index) => {
        return (
          <div key={r.id}>
            <h1>{r.name}</h1>
            <h2>ingredients</h2>
            <div className="content">{r.ingredients}</div>
            <h2>steps</h2>
            <div className="content">{r.steps}</div>
            <button className="button" onClick={() => deleteRecipe(index)}>
              delete
            </button>
          </div>
        );
      })}
    </div>
  );
}

We have the recipe state which is used to store the form data.

recipes has the recipe entries.

Then we define the addRecipe function that lets us add a recipe.

Inside it, we call e.preventDefault() to do client-side form submission.

Then we check if name , ingredients , and steps are set.

If they are, then we call setRecipes to add the entry.

We pass in a callback that takes the existing recipes value, then we return a copy of it with an object that has the new entry at the end.

We call uuidv4 to return a unique ID for the new entry.

The deleteRecipe function calls setRecipes with a callback that takes the existing recipes . Then it returns a copy of it without the entry at the given index .

Below that, we add the style element to style the steps.

And we have the form with the onSubmit prop set to addRecipe to add an entry when we click on the button with type submit .

Inside the form, we have the inputs with an onChange prop that are set to functions that call setRecipe to set the inputted value to a property in the recipe object.

Below the form, we render the recipes values into a div.

Inside it, we show the name , ingredients , and steps .

And below that, we have a button that calls deleteRecipe with the index when we click it.

Conclusion

We can create a recipe app with React and JavaScript.

Categories
React Projects

Create a PIN Pad with React and JavaScript

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a PIN pad with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app pin-pad

with NPM to create our React project.

Create the PIN Pad

To create the PIN pad, we write:

import React, { useState } from "react";

export default function App() {
  const [pin, setPin] = useState("");

  return (
    <div>
      <div>{pin}</div>
      <div>
        <div>
          <button onClick={() => setPin((pin) => `${pin}1`)}>1</button>
          <button onClick={() => setPin((pin) => `${pin}2`)}>2</button>
          <button onClick={() => setPin((pin) => `${pin}3`)}>3</button>
        </div>
        <div>
          <button onClick={() => setPin((pin) => `${pin}4`)}>4</button>
          <button onClick={() => setPin((pin) => `${pin}5`)}>5</button>
          <button onClick={() => setPin((pin) => `${pin}6`)}>6</button>
        </div>
        <div>
          <button onClick={() => setPin((pin) => `${pin}7`)}>7</button>
          <button onClick={() => setPin((pin) => `${pin}8`)}>8</button>
          <button onClick={() => setPin((pin) => `${pin}9`)}>9</button>
        </div>
        <div>
          <button onClick={() => setPin((pin) => pin.slice(0, pin.length - 1))}>
            &lt;
          </button>
          <button onClick={() => setPin((pin) => `${pin}0`)}>0</button>
          <button onClick={() => setPin("")}>C</button>
        </div>
      </div>
    </div>
  );
}

We create the pin state to hold the string that’s created when we click the buttons.

Then we show the pin value.

And then we add the buttons which have the onClick prop set to a function that calls setPin with a callback that returns the pin string.

The < button has a setPin callback that returns the pin string with the last character removed.

And the C button has a setPin callback that resets pin to an empty string.

Conclusion

We can create a PIN pad easily with React and JavaScript.