Using JavaScript regular expressions, replace either one word or another with the option of having white spaces between the words

I am currently facing an issue with a string that contains multiple words. I need to replace a specific phrase, but there are several similar phrases that also need replacement.

Below are the strings that require replacement (or removal):

  • "fox jumps over the lazy dog"
  • "fox jumps over the lazy cat"
  • "fox jumpa over the lazy cat"
  • "fox jumpaoverthe lazy cat" (note: some spaces might be missing between words)
  • The replacement should be case insensitive and global

    Example 1: var str = "The quick brown fox jumpa over the lazy dog"; // the result would be "The quick brown "

    Example 2: str = "The quick brown fox jump over the lazy dog"; // the result would be "The quick brown "

    Example 3: str = "The quick brown fox jump over the lazy cat"; // the result would be "The quick brown "

    Example 4: str = "The quick brown fox jumpa over the lazy cat"; // the result would be "The quick brown "

    Example 5: str = "The quickbrownfoxjumpaoverthe lazy cat"; // the result would be "The quick brown "

I have tried the following code without success:

    let str1 = "The quick brown fox jumpa overthe lazy cat";
    let reg = /The\s*quick\s*brown\s*fox\s*jump[s|a]\s*over\s*the\s*lazy [\bcat\b|\bdog\b]/gi;
    let res = str1.replace(reg, "");
    console.log(res); //should be empty

    str1 = "The quickbrownfox jumps overthe lazy cat";
    res = str1.replace(reg, "");
    console.log(res); //should be empty

Answer №1

For those wanting to extract specific text, the regex below can be quite helpful:

The\s*quick\s*brown\s*fox\s*jump(s|a)?\s*over\s*the\s*lazy\s*(cat|dog)/gi

let str1 = "The quick brown fox jumpa overthe lazy cat";
let reg = /The\s*quick\s*brown\s*fox\s*jump(s|a)?\s*over\s*the\s*lazy\s*(cat|dog)/gi;
let res = str1.replace(reg, "");
console.log(res); //should return empty string

str1 = "The quickbrownfox jumps overthe lazy cat";
res = str1.replace(reg, "");
console.log(res); //should also return empty string

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 causing my checkboxes to deactivate other selections?

My checkboxes are causing a dilemma where changing the value of one checkbox sets all others to false. To address this issue, I am considering implementing a solution in my validate.php file that would only update the intended checkbox value. If this appro ...

Removing an element from an array within MongoDB

After closely examining my mongodb data structure, it appears like this: [ { "_id": "582bc918e3ff1bf021ae8b66", "boardName": "Test Board", "created_at": 1479264483957, "__v": 0, "person": [ { "name": "Steve", "w ...

Using AngularJS routing with an Express 4.0 backend API

Recently, I began working on an application utilizing Express 4.0 server. Following a tutorial on scotch.io (http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4), I structured the routes to support a backend api serving an An ...

Retrieve solely the text content from a JavaScript object

Is there a way to extract only the values associated with each key in the following object? const params = [{"title":"How to code","author":"samuel","category":"categoery","body":"this is the body"}] I'm struggling to figure out how to achieve this. ...

Display error messages upon submitting the form

I am currently working on an Angular 6 Form with validation. My main goal is to display error messages only after the form has been submitted. It is crucial that these messages remain constant while the user types in the input field. For instance, if a use ...

What causes an asynchronous function to exhibit different behavior when utilized in conjunction with addEventListener versus when manually invoked?

I was delving into the concepts of async and await keywords and decided to create a basic demonstration using an HTML file and a corresponding JS file. In my example, I defined two promises - promise1 and promise2. The handlePromises function uses async/ ...

What are some ways to design scrollbars with a Google Wave-like style?

Is there a way to design scrollbars similar to the ones found in Google Wave? They seem to save space and have an appealing look. I am interested in implementing these customized scrollbars on a div element, just like how Google Wave utilizes them. https: ...

Implementing a Tab on Firefox Extension Upon Window Load

I have a requirement to add a tab whenever a new Firefox window is loaded for my bootstrap extension. Below is the code snippet I am using: var WindowListener = { setupBrowserUI: function(window) { window.gBrowser.selectedTab=window.gBrowser.a ...

When there is a lack of internet connection, WKWebView does not reach completion or timeout

When using a WKWebView to navigate to a local HTML page, I encountered an issue with a remote Javascript asset tag that never finished downloading. This occurred even when the iOS device was not connected to the internet or had slow internet speeds. The p ...

The value from the angular UI bootstrap datepicker is unavailable when using a JQuery expression

I have a question regarding the datepicker feature from the Angular UI bootstrap library. The documentation can be found here. After selecting a date using the datepicker, I am facing an issue with retrieving the text input using jQuery expressions. When ...

What is the best way to prevent npm install from running in nested workspace directories?

I've recently started utilizing npm workspaces in my project. Here is the structure of the app: . +-- package.json -- packages +-- a | -- package.json -- b -- package.json The npm install script should ideally be executed from ...

Looping through data in Vue.js with a specific condition

There is an object structured like this: groupedContacts: { 4: [ {name: 'foo'}, {name: 'bar'} ], 6: [ {name: 'foo bar'}, ] } Additionally, we have another array: companyList.models: models: [ ...

Is it possible to show an image without altering the Box dimensions?

Hi there, I am currently working on designing a footer and I have encountered an issue. I want to add an image in a specific position, but when I do so, it affects the size of the box. I was wondering if there is a way to set the image as a background or b ...

Encountered a JavaScript error while using Internet Explorer

My web and Jquery plugins are working flawlessly on various browsers such as Firefox, Chrome, Safari (Windows & OSX), and Android. However, they encounter issues with Windows and Internet Explorer as some JavaScript fails to load. It's frustrating tha ...

Is there a way for me to choose the item from the search dropdown so that it fills in the search input field automatically?

Upon typing a word into the search input field, a list of suggestions will appear below. https://i.sstatic.net/etOBI.png Is there a way for me to select a word from the list like Maine (ME) and have it automatically fill the search input field? What chan ...

Transform the single backslash in an R character string into a properly formatted JSON string

I'm facing an issue with a string in R where quotation marks are being escaped: my_text = {\"stim\":[\"platery\",\"denial\",\"generic\"]} Using cat() yields the following result: {"stim":["platery","denial"," ...

creating dynamic data objects in ajax calls

https://jsfiddle.net/c7n34e3x/1/ from data, data1, and data2, only data is functioning, but it lacks dynamism. This method works as intended. var settings = { "async": true, "crossDomain": true, "url": "https://domain/api/v2/playlists/", ...

Binding attributes in knockoutjs following an AJAX request

The objective Incorporate the attr binding of KnockoutJS following an AJAX call. The dilemma Check out the code snippet below: $.ajax({ url: "/Products/List?Output=JSON", dataType: "json", success: function (data) { $.each(data, fun ...

The $scope.$watch function does not activate with each individual change

Yesterday, I realized that in my angularJS 1.4.8 application, the $scope.$watch doesn't trigger on every change causing a bug to occur. Is there a way to make it work on every change immediately? For example, in this code snippet, I want the function ...

Generate a regex pattern that identifies a word with a space, followed by a string of exactly 8 characters

Exploring the world of regular expressions is a new adventure for me. I’m on a quest to find sentences that contain an exact given word followed by a space, and then an alphanumeric string starting with a number that is exactly 8 characters long. The e ...