Ways to eliminate a group of words from a string using JavaScript

I have developed a unique function that efficiently deletes specified words from a given string. Here is the function:

 var removeFromString = function(wordList, fullStr) { 
  if (Array.isArray(wordList)) {
    wordList.forEach(word => {
      fullStr = fullStr.split(word).join('');
    });
  } else {
    fullStr = fullStr.split(wordList).join(''); 
  }
  return fullStr;
};

To use this function, you can follow these examples:

 console.log( removeFromString("Hello", "Hello World") ); // World
 console.log( removeFromString("Hello", "Hello-World") ); // -World

However, a common issue arises with scenarios like:

 var str = "Remove one, two, not three and four"; 

In this case, we need to delete "one", "two", and "four". To achieve this, you can do the following:

var c = removeFromString(["one, two," , "and four"], str); // Remove not three
 console.log(c); // Remove not three

As you can see, this updated function enables you to remove multiple words at once by passing an array of words. This enhances the functionality of the removeFromString function. Feel free to give it a try!

Answer №1

You can utilize the join method to dynamically build a regex from an array and then replace the matching values in a string

function removeFromString(array, string){
  let regex = new RegExp("\\b"+array.join('|')+"\\b","gi")
  return string.replace(regex, '')
}

console.log(removeFromString(["one, two," , "and four"],"Remove one, two, not three and four" ));
console.log(removeFromString(["one" , "and four"],"Remove one, two, not three and four" ));
console.log(removeFromString(["Hello"], "Hello World") )


If your word to match can contain meta-characters, you can enhance the previous function like this

function escape(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};

function removeFromString(array, string) {
  let escapedArray = array.map(val=> escape(val))
  let regex = new RegExp("(?:^|\\s)"+escapedArray.join('|') + "(?!\\S)", "gi")
  return string.replace(regex, '')
}

console.log(removeFromString(["one, two,", "and four"], "Remove one, two, not three and four"));
console.log(removeFromString(["one", "and four"], "Remove one, two, not three and four"));
console.log(removeFromString(["Hello"], "Hello World"))
console.log(removeFromString(["He*llo"], "He*llo World"))
console.log(removeFromString(["Hello*"], "Hello* World"))

Answer №2

Here is an alternative method that utilizes the reduce function:

function removeWordsFromString(words, str) {
  return words.reduce((result, word) => result.replace(word, ''), str)
}

const str = "Remove one, two, not three and four"
const result  = removeWordsFromString(["one, two, " , "and four"], str)

console.log(result)

Answer №3

Check out this solution:

function removeWordsFromArray(array, string){
    array.forEach(word => string = string.replace(word, ''));
    return string;
}

Answer №4

Iterating through an array of words using forEach, each word is removed from the sentence by replacing it with an empty string. 

Answer №5

Here is an example of what you should use:

function removeWordsFromArray(arrayOfWords, sentence){

    for(var i=0; i<arrayOfWords.length; i++){

        sentence = removeWordFromString(arrayOfWords[i], sentence);

    }
    return sentence;
}

This function iterates through the words in the array and removes them individually.

Answer №6

give this a go

function updateText(text,list)
  {
    $.each(list,function(i,item){
    text=text.replace('Hello', item);
    });   
  }
  
  /*Try out this function like this */
updateText(yourtext,arrayOfWords);
or updateText(yourText,{"word1","word2"});

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

What is the best method for modifying an array variable?

I am working with a variable array named data for my IGcombobox datasource. I need to update the array when I click on my #select element, but the current code is not changing the variable. Is there a way to achieve this without using PHP? <div id="c ...

What is the best way to split text copied from a textarea into <p> paragraphs with an equal number of characters in each?

Check out this JSFiddle version I've found a JSFiddle example that seems perfect for my current project needs. However, I'm wondering how to modify the code to ensure that each paragraph is evenly divided with the same number of characters and a ...

Modify a field within MongoDB and seamlessly update the user interface without requiring a page refresh

I am currently working on updating a single property. I have various properties such as product name, price, quantity, supplier, and description. When sending the updated quantities along with all properties to MongoDb, I am able to update both the databas ...

Tips for resolving the Error: Hydration issue in my code due to the initial UI not matching what was rendered on the server

export default function Page({ data1 }) { const [bookmark, setBookmark] = useState( typeof window !== 'undefined' ? JSON.parse(localStorage.getItem('bookmark')) : [] ); const addToBookmark = (ayatLs) => { s ...

An introduction to integrating Paged.js with Vue.js3

index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> < ...

How can PHP be used to iterate through numbers and retrieve letters?

Looking to start at a specific point in the alphabet and iterate through while skipping characters? I attempted this with the loop below, but now I'm wondering - how can I increase the starting point by 3 characters? $start = 'G'; for ($i = ...

Having issues with $timeout functionality in angular.js

I've implemented $timeout in my controller but it doesn't seem to be functioning correctly. app.controller("Friendsrequests",['$http','$log','$location','$timeout','$scope', function($http,$log,$ ...

Reactivity in Vue.js powered by ES6 classes

I am attempting to create a computed property in Vue.js that is associated with an ES6 class. Here is an example of my Vue instance setup: ... props: ['customClass'], computed: { localClass: { get() { return this.custom ...

How to turn off and on all elements within a Div tag

Is there a way to disable all elements within a Div tag? I've managed to disable input types successfully, but I'm struggling with links. I attempted the solution provided here, but it didn't work. Here's the code snippet that worked f ...

Experiencing difficulties with Magento operations

Currently facing an issue while attempting to set up Magento on my server. I have transferred all files from another server to mine, but now encountering an error. Could this be related to the symlinks I generated or is it caused by something else? Encoun ...

Transitioning from ng-repeat filter to Typescript

As I migrate my project from AngularJS to modern Angular 8, one of the steps is converting JavaScript code to TypeScript. During this process, I encountered a challenging issue with the `ng-repeat` filter feature. Initially, my HTML template looked like t ...

Controlling User Roles within a React JS Application

Which libraries do you rely on for managing user roles in your React projects? All suggestions and advice are appreciated. Specifically, I am interested in controlling the visibility of different application components based on the user's role. ...

Ways to resolve the issue of the 'setConfirmDelete' property not being found on type 'JSX.IntrinsicElements' in React.js

index.tsx const setConfirmDelete = (state, close) => { return ( <Modal show={state} onHide={close}> <Modal.Header> <Modal.Title>Title</Modal.Title> </Modal.Header> <Modal.Body> 'T ...

Using Rails and Haml to Implement Smooth Scrolling with Jquery and CoffeeScript

Looking to accomplish a straightforward task using CoffeeScript, Rails, and Haml. While I don't have much experience with CoffeeScript, I'm eager to experiment. The goal is to have the view scroll to a specific div id when a button is pressed. A ...

javascript game for reversing an array

in case(po==true){ snake_array.reverse(); var i=0; var c=snake_array[i]; //drawing the head draw_head(c.x,c.y); for(i=1;i<snake_array.length;i++){ //drawing the body var c=snake_arr ...

Implementing Ionic 4 with HTML2Canvas technology

Looking for a way to convert HTML into an image within an Ionic 4 application. I attempted to use html2canvas, however, it was unsuccessful and displayed the following message in the console: https://i.sstatic.net/4b4Sm.png Below is the code snippet I use ...

Issue encountered when displaying an organized list in next.js

I have been working on rendering an array of items in descending order based on their values. Everything seems to be functioning correctly, but I keep encountering an error that reads Error: Text content does not match server-rendered HTML. whenever I tr ...

The filtering and sorting features of Ng-table do not seem to be working properly when dealing with grouped data

Currently, I am in the process of learning angular.js and have recently started using the ng-table directive. While I have successfully managed to group my data and display it using ng-table, I seem to be facing issues with sorting and filtering the data. ...

Having trouble with Bootstrap 5 Carousel not sliding to the next image? Learn how to fix this issue by upgrading from Bootstrap 4 to Bootstrap 5

Having downloaded both the compiled css and js and the source files of the bootstrap 5 library, I've experimented with both. While the css seems to load fine, I'm struggling to get this example to function. It's from a bootstrap 4 related po ...

Ways to resolve eslint typedef error when using angular reactive forms with form.value

I am facing an issue with my formGroup and how I initialized it. Whenever I try to retrieve the complete form value using form.value, I encounter an eslint error related to typecasting. userForm = new FormGroup<user>({ name: new FormControl<st ...