How can we delete a specific word from a string if it is found in an

Facing a seemingly simple problem that's proving tricky to solve.

I have an array of product names and a sentence. The goal is to remove any product names from the sentence if they appear in it.


const products = ["premium t-shirt", "t-shirt", "sweatshirt", "baseball tee", "v-neck t-shirt", "long sleeve t-shirt", "raglan baseball tee", "pullover hoodie", "tank top", "zip hoodie",
"hoodie", "shirt", "tee", "tshirt"];

const name = "I'd Rather Be Beekeeping Save The Bees Honey Bee Beehive Zip Hoodie T-Shirt".toLowerCase();
let strippedName;
products.forEach(p => {
    if(name.includes(p)) strippedName = name.replace(p, "");
});

The code successfully removes the word shirt but not t-shirt as expected. However, there is also the challenge of iterating over the strippedName variable rather than the original name.

Any suggestions on how to improve this solution?

Answer №1

Each time you override `strippedName` with the latest replaced value from the `name` string, but what you actually need is to remember the last replaced value when replacing the next one.

const products = ["premium t-shirt", "t-shirt", "sweatshirt", "baseball tee", "v-neck t-shirt", "long sleeve t-shirt", "raglan baseball tee", "pullover hoodie", "tank top", "zip hoodie","hoodie", "shirt", "tee", "tshirt"];
const name = "I'd Rather Be Beekeeping Save The Bees Honey Bee Beehive Zip Hoodie T-Shirt".toLowerCase();
let strippedName = name;

products.forEach(p => {
  if (name.includes(p)){
   strippedName = strippedName.replace(p, "");
  }
});

console.log(strippedName)

Answer №2

Change the array into a case insensitive, global regular expression.

const items = ["item1", "item2", "item3", "item4"];

const itemName = "Sample Item Name";

let modifiedName = itemName.replace(new RegExp(items.join("|"), "gi"), "");

console.log(modifiedName);
If any of the items characters are special characters for regular expressions, they will be escaped first.

Answer №3

Here is a revised version for you:

let items = ["premium hat", "hat", "sunglasses", "baseball cap", "beanie", "visors", "snapback cap", "beret", "fedora", "cap",
"bowler hat", "bucket hat", "trilby"];

var name = "I Love My Hats Stylish Fedora Baseball Cap Snapback Visor Beret Hat".toLowerCase();
let strippedName = name;
items.forEach(i => {
    if(name.includes(i)){
        strippedName = strippedName.replace(i, "");
    } 
});

Answer №4

let items = ["premium t-shirt", "t-shirt", "sweatshirt", "baseball tee", "v-neck t-shirt", "long sleeve t-shirt", "raglan baseball tee", "pullover hoodie", "tank top", "zip hoodie",
"hoodie", "shirt", "tee", "tshirt"];

const itemName = "I'd Rather Be Beekeeping Save The Bees Honey Bee Beehive Zip Hoodie T-Shirt".toLowerCase();
let modifiedName = itemName;
items.forEach(item => {
  if(modifiedName.includes(item)) {
    modifiedName = modifiedName.replace(item, "");
  }
});
console.log(modifiedName);

Answer №5

When using the includes method, keep in mind that it is case sensitive. This means 'T-shirt' and 't-shirt' will be treated as different strings. To avoid any issues, consider converting the string to either uppercase or lowercase before using the include method.

Here is an example:

const products = ["premium t-shirt", "t-shirt", "sweatshirt", "baseball tee", "v-neck t-shirt", "long sleeve t-shirt", "raglan baseball tee", "pullover hoodie", "tank top", "zip hoodie",
"hoodie", "shirt", "tee", "tshirt"];

Applying this concept to a specific scenario:

const name = "I'd Rather Be Beekeeping Save The Bees Honey Bee Beehive Zip Hoodie T-Shirt";
const n = name.toUpperCase();
let strippedName;
products.forEach(p => {
    if(n.includes(p.toUpperCase())) strippedName = new.replace(p, "");
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When the link_to element is clicked, use AJAX to replace the content of a specific

I was wondering about a modification to the link in view/users/show: <%= link_to "Photos (#{@user.photos.count})", user_path(@user), id: "photo_link", remote: true %> My goal is to dynamically change [1..6] to [1..-1] without having to rerender the ...

The middleware code remains dormant and is left untouched

I am encountering an issue with this code that is supposed to create a folder if it doesn't already exist. When I debug and set a breakpoint on fs.mkdir, the code does not enter into it. Do you have any idea what could be causing this problem? ... ap ...

What is the best way to refresh or render a list in a React application?

While attempting to update the calendar days by using useState, I encountered a "too many re-renders" error. Even though the list was updated correctly, the component did not render on the screen as expected. I am struggling with figuring out how to update ...

What could be causing my Alert component to keep triggering repeatedly?

This is my custom React Native script. import React, { useState, useEffect } from 'react'; import { Alert, View, Image, StyleSheet, Animated, Easing, TouchableOpacity, Text, ScrollView, ImageBackground, Dimensions, TextInput } from 'react-na ...

Unraveling exceptions in Node.js akin to handling them in Java

I'm seeking to develop a node application and I need guidance on exception handling. In Java, we utilize the exception class for this purpose. How can I achieve something similar in node? Are there any libraries available specifically for handling exc ...

A guide on ensuring all necessary keys are present in a JSON document using Node.js

I have been researching various methods for efficiently checking if a key exists in a JSON file. The challenge I am facing is related to optimizing this process. My current workflow involves users uploading a CSV file which I then convert into JSON format ...

Best practices for effectively dismantling a Paper.js Scope

In my web project, I am utilizing multiple Paper.js canvases by creating a new scope for each of them. Due to the AJAX-driven nature of the site, I need to get rid of unnecessary instances when switching between subpages. Unfortunately, there is no built-i ...

Retrieve the access ID from the conn.query result

When I run a SQL query, I need to extract the primary key (id) of the event returned so I can use it in another SQL query. However, attempting to access it using result.insertId returns null for the event object. Even logging result.insertId only outputs ...

Different ways to automatically trigger a function in JavaScript

There are various ways to trigger a function automatically in javascript when a page loads. I am interested in knowing which method is considered the most effective and reliable. If you have a unique approach that differs from others, please share it here ...

Tips for fetching a response after sending an ajax request using XMLHttpRequest

/* The following **frontend** function is executed to transmit a new post (in JSON) to the Node server */ addPost(postData) { const xhr = new XMLHttpRequest(); xhr.open('POST', `${process.env.REACT_APP_BACKEND}/posts`); xhr.setRe ...

Ways to dynamically toggle visibility and hide elements by clicking outside the specified div

I have a div that, when clicked, displays a contact us form. This form toggles between being visible and hidden. How can I make it hide when clicked on another part of the document? Here is the code: function showContactForm(){ var formWidth = &apos ...

Making AJAX requests with Laravel using the XMLHttpRequest object is a

When using Laravel to upload a file and create a progress bar with ajax requests, the form action routes to the controller in this way: <form action="{{ URL::route('upload-file-form-post') }}" method="POST" enctype="multipart/form-data"> ...

Removing a selected row from a data table using an HTTP request in Angular 2

I am working with a table that has data retrieved from the server. I need to delete a row by selecting the checkboxes and then clicking the delete button to remove it. Here is the code snippet: ...

Preventing page navigation in JavaScript: Why it's so challenging

I am encountering an issue with a link element that I have bound a click event to (specifically, all links of a certain class). Below is an example of the link element in question: <a id="2" class="paginationclick" style="cursor: pointer;" href=""> ...

Is there a way for me to make my Note element automatically update whenever I modify its text content?

Feeling a bit stuck with my project, especially this part. I'm currently using React to develop a notes application, and I'm having trouble updating the note when changing the text within the modal popup. The commented sections are where I need h ...

Unable to allocate a second item to an existing one

Encountering an unusual issue while trying to assign an item a second time. Initial scenario: I am working with a jqxTree containing various items as shown below: - apple - oracle - microsoft When I drag and drop one item into another, the structure loo ...

Creating multiple JSON files on disk from a JSON array using NodeJS

My goal was to utilize NodeJS for reading a JSON array from a file, and then save each JSON object into multiple separate JSON files on the disk. However, I encountered an error message stating EMFILE: too many open files. The array in question contains ...

Is there a way to narrow down Drive API list results based on a specific domain that has write permission?

I am currently working on retrieving a list of files from the drive API using a service account, with permissions granted to a specific domain for editing. While I have successfully implemented this feature for individual emails, I am facing a challenge in ...

Utilizing the identical modal for Add/Edit functionality within AngularJS

Recently, I started working with AngularJS and I am in the process of creating a simple project that involves creating, reading, updating, and deleting countries. The code is functioning correctly overall. However, I have encountered an issue regarding th ...

Troubleshooting Problem with Express Server Routing

I'm currently facing an issue with my error handling while trying to implement a new route to retrieve a user by their id. Below is the code snippet for this specific route. const express = require('express'); require('./db/mongoose&a ...