Javascript regular expression fails to find a match

Is there a way to match all strings except for the ones containing '1AB'? I attempted it but it returned no matches.

var text = "match1ABmatch match2ABmatch match3ABmatch";
var matches = text.match(/match(?!1AB)match/g);
console.log(matches[0]+"..."+matches[1]);

Answer №1

When using lookarounds in regex, the text is not consumed and the regex index does not move when their patterns are matched. For more information, check out Lookarounds Stand their Ground.

To match the text, you still need to use a consuming pattern such as \w+ for word matching. Alternatively, you can use \S+ for one or more non-whitespace characters. If any characters, including line breaks, need to be matched, use .+ (matches 1 or more characters other than line break characters) or [^]+ (matches even line breaks).

var text = "match100match match200match match300match";
var matches = text.match(/match(?!100(?!\d))\w+match/g);
console.log(matches);

Details of the Pattern

  • match - a literal substring
  • (?!100(?!\d)) - a negative lookahead that fails the match if immediately to the right there is the substring 100 not followed by a digit. If you want to fail matches where the number starts with 100, remove the (?!\d) lookahead.
  • \w+ - 1 or more word characters (letters, digits, or _)
  • match - a literal substring

Check out the online regex demo.

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

Get an MP4 on your iPhone (iOS) by downloading it from a link on a webpage

Despite trying various methods such as the HTML5 download tag, JavaScript, JQuery, and other techniques, I have not been able to successfully download a file to the Album. While photos can be saved by long clicking and selecting "Save Image", videos do n ...

Creating a default option in a Select tag with React when iterating over elements using the map method

After learning that each element in the dropdown must be given by the Option tag when using Select, I created an array of values for the dropdown: a = ['hai','hello','what'] To optimize my code, I wrote it in the following ...

What is the best way to remove multiple IDs from req.params using Sequelize?

Is there a way to handle req.params that contain multiple IDs? I need to search for and delete these multiple IDs. Here is the code snippet: const ids = req.params; const masterFunders = await masterFunder.findOne({ where: { id: ids ...

Modify the width measurement from pixels to percentage using JavaScript

Looking for some help with a content slider on my website at this link: . I want to make it responsive so that it adjusts to 100% width. I managed to make it responsive by tweaking some code in the developer tools, but now I'm stuck. The bottom two p ...

Is there a way for me to extract the document title from firebase?

I have been trying to use this component to retrieve data, but I am encountering an issue where I cannot fetch the name of the document "sampleCloudFunction" under CloudFunctionMonitor (see image) from the database and display it. Using docRef.id does not ...

Send a request to templateUrl

After experimenting with AngularJS, I decided to create a dynamic route system that funnels all routes through a single PHP file. This was motivated by my desire to prevent users from accessing raw templateUrl files and seeing unstyled partial pages. Prio ...

Tips for interacting with a custom web component using Selenium WebDriver

As a newcomer to writing selenium tests, I am attempting to create an automated test for a carousel feature on our homepage. The objective is to click on one of the carousel navigation buttons and then confirm that a specific inline style has been applied ...

Ways to store information in variables and use it across different blocks in Cypress

Is it feasible to store data in variables and reuse them in other blocks within Cypress.io? For instance, imagine I have a unique name for a device. I aim to retrieve this information and then verify if the title in a new window includes that particular de ...

retrieveValue() for SelectionDropdown

I have a simple task - I just need to retrieve the name of the Company and store it in the database. Initially, I was able to achieve this using plain text and the code snippet below: sport: this.refs.company.getValue(), which worked perfectly. However, ...

Using discord.js within an HTML environment can add a whole new level of

I'm in the process of creating a dashboard for discord.js, however, I am facing difficulties using the discord.js library and connecting it to the client. Below is my JavaScript code (The project utilizes node.js with express for sending an HTML file ...

Is it necessary to define module.exports when using require() to import a file?

While setting up my Express server, I am using Babel to transpile my ES6 files seamlessly. In my vanilla JS server.js file, I include require('babel-core/register') and require('./app'). Within my ES6 file app.js, I handle all the usua ...

Text input fields failing to record text

I've set up a forum using react-redux and material ui, but I'm facing an issue where the text fields are not updating based on state changes. When users try to type in the text field, nothing seems to happen. onChange={e => onT ...

Creating HTML input elements dynamically using Javascript

<body> <form action="insertquestion.php" method="POST"> <script> function generateInputs(){ var prefix = "answer"; var number = 1; for(var i = 0; i < 5; i++){ ...

Add the file retrieved from Firestore to an array using JavaScript

Trying to push an array retrieved from firestore, but encountering issues where the array appears undefined. Here is the code snippet in question: const temp = []; const reference = firestore.collection("users").doc(user?.uid); firestore .collec ...

Unable to set the height for ul/div elements

I'm struggling to make my navbar appear when I click the "menu button". The div seems to be present in the code, but with a height of 0. Here's the relevant section of the code causing the issue. Any suggestions on how I can resolve this? var ...

Preventing the removal of a choice by disabling it in the selector

I have a unique selector that is designed like this: <select id="patientSelector"> <option disabled selected style='display: none;' id="select0"> New Patients to Come</option> <option id="select1"></opt ...

What is the best way to merge javascript files and have them load after the page has already loaded on an asp.net site?

I recently came across a helpful SE Post that discussed combining external javascript files for better optimization, which is something I'm interested in. Following recommendations, I have converted internal javascripts into an external .js file and s ...

Is it possible to alter the name of a slot before displaying the element in the shadowDOM, depending on the slot utilized in the DOM?

In my project, I am working on implementing different features for both desktop and mobile devices. Some of these features can be replaced by slots. My goal is to have a slot that can be either replaced by a desktop slot called poster-foreground, or a mobi ...

Using jQuery .animate() leading to erratic input movements

I am currently utilizing jQuery's .animate() feature to create a smooth animation effect on the width of a <div> element when a child <input> is in focus. Nevertheless, I'm encountering an issue where the input field jumps up and down ...

Parsing DXF files using only plain JavaScript

Currently, I am immersed in a CNC project and aiming to convert DXF files into objects using JS. Initially, I attempted using SVGs but the results were not as expected - instead of shapes, the drawings exported as lines (e.g., a square appearing as four se ...