How can I identify a pattern in JavaScript that may include a certain character but cannot end with it using regex?

I am a beginner in the world of regular expressions. Despite my efforts to find a solution for my specific case, I have not been successful. I have tested several ideas that I came across, but none of them have worked for me.

I have a unique repetitive pattern that I have attempted to match. While I have made progress, I have not yet found the exact solution. Here is the RegEx I have used:

/((([a-zA-IK-Z][a]?)[\d]{1,3}[a-zA-Z]?)(-)?){1,}/g

My pattern examples:

Aa200-B300-M52A-G5-Aa50   (matches as expected)
Aa200-B300-M52A-G5-A      (does not match as expected)
Aa200-B300-M52A-G5-Aa     (does not match as expected)

While this pattern works well for most cases, I want it to exclude scenarios like the following example:

Aa200-B300-M52A-     (ending with -)

What is the best approach to achieve this desired outcome?

Answer №1

Feel free to utilize this regular expression pattern:

/^[a-zA-IK-Z]a?\d{1,3}[a-zA-Z]?(?:-[a-zA-IK-Z]a?\d{1,3}[a-zA-Z]?)*$/gm

Check out the RegEx Demo here

Ensuring that - only appears in the middle and not at the end is achieved by positioning it at the beginning of the repeating non-capturing group.

Answer №2

Give this a shot - it's set up so that if there is a next group, there should be a "-" before it. I also adjusted your number groups from {1,3} to {0,3} because the expected matches may not always contain a number (2nd and 3rd cases). Let me know how it goes!

const regex = /^([a-zA-IK-Z]a?[\d]{0,3}[a-zA-Z]?)(-([a-zA-IK-Z]a?[\d]{0,3}[a-zA-Z]?))*$/;

console.log("Should match");
console.log("Aa200-B300-M52A-G5-Aa50".match(regex));
console.log("Aa200-B300-M52A-G5-A".match(regex));
console.log("Aa200-B300-M52A-G5-Aa".match(regex));

console.log("Should not match");
console.log("Aa200-B300-M52A-G5-".match(regex));

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

Pick the item when the checkbox is selected

I am currently attempting to toggle the visibility of a select element based on whether a checkbox is checked or not, but it doesn't seem to be working as expected. My desired functionality is for the select element to be hidden upon page load and th ...

What is the best approach to comparing two times in JavaScript to ensure accuracy after an NTP time update?

We are facing an issue with a JavaScript function that retrieves the start and end times of two events: var startTime = new Date().getTime(); // A lengthy task is executed var endTime = new Date().getTime(); The problem we encountered is that getTime() s ...

Having issues debugging in the browser as React seems to be undefined

I am trying to implement a Context system to store the login user's name and use it for protected routes. context.js import React from 'react'; const axios = require('axios'); export const AuthContext = React.createContext(null); ...

Is there a way for me to store the retrieved information from an API into a global variable using Node.js?

function request2API(option){ const XMLHttpRequest = require('xhr2');//Cargar módulo para solicitudes xhr2 const request = new XMLHttpRequest(); request.open('GET', urlStart + ChList[option].videosList + keyPrefix + key); request. ...

The pattern() and onkeyup() functions are unable to function simultaneously

When trying to display a certain password pattern using regex while typing in the fields, I encountered a problem. The onkeyup() function works for checking if both passwords match, but it causes the pattern info box not to appear anymore. I'm curiou ...

New Trainee - Error: document has not been defined

Encountering an Error message while attempting to run Intern tests from the test files directory. The structure of the directory is as follows: test resources rest pickup.js cashManagement.js gitignore intern.js packages.js ...

Next.js 13 React Server Component not displaying updated data upon build completion

I have a React Server Component that retrieves its data at build time and does not reload it while the site is running. I expected it to fetch the data once when the server component is first rendered. Is there a way to force this server component to relo ...

Exploring the contents of variables within the forEach iteration

One issue I've encountered involves accessing variables from a forEach loop that iterates over an array of objects, and trying to use those variables outside the loop. I attempted to declare variables and assign them values from the loop, but I found ...

Graphic selectors: a new take on radio buttons

I've been attempting to make this work, but it's not functioning correctly. Below is the CSS code: .input_hidden { position: absolute; left: -9999px; } .selected { background-color: #000000; } #carte label { display: inline-bl ...

What are the recommended methods for injecting db and logger into routes in an Express application?

When working with Express and needing to pass single instance references like a logger or database to routes, I have come across three options. The first option is to attach it to the request object through a middleware: app.use(function(req,res,next){ re ...

Each Jest test file should have a specified window.location

After upgrading to Jest 22, I encountered an issue with mocking window.location. Previously, this method worked fine but stopped working after the update. Object.defineProperty(window.location, 'href', { writable: true, value: 'http ...

What could be causing "Unknown property" errors when using unicode property escapes?

The MDN website provides examples of matching patterns with unicode support, such as: const sentence = 'A ticket to 大阪 costs ¥2000 ...

Retrieving Gravity Forms AJAX Confirmation Message programmatically in JavaScript instead of displaying it

I have set up the Gravity Forms plugin in my Wordpress website and implemented the AJAX feature on my form. Currently, upon submission, a Confirmation message is displayed automatically. However, I am interested in retrieving the content of this message us ...

Build.js.erb requesting a partial script task

Struggling to make my create action function accurately in my rails app. The following two lines work as intended: $('#pit_form').remove(); //remove form $('#new_link').show(); //show new link again They successfully remove the form ...

The search button is malfunctioning after I submit search data and generate dynamic HTML using axios

When a user clicks on the search button, I retrieve the input value and then use axios to send a GET request with the search data. Everything works fine, but when I query the database and dynamically create data from the mongoose data, the page reloads w ...

What is the best method for converting IDs into objects within ng-options in Angular?

Is there a way to dynamically use an array of IDs as the source of my ng-option directive inside of select? Instead of creating an array of objects with corresponding IDs, I am wondering if there is a method to set a function as the source of ng-option. ...

What is causing this issue with the ajax call not functioning correctly?

$(document).ready(function(){ $('.clickthetext').click(function(){ $.post("submit.php", $("#formbox").serialize(), function(response) { $('#content').html(response); }); return false; }); ...

Unusual actions observed with that particular button

Currently, I am working on creating a pomodoro clock using Codepen. While I acknowledge that my code isn't flawless yet, I have encountered a peculiar behavior with the Start button. When I click on it once, the timer starts as expected. However, if I ...

Exploring the Issue of Flickering in 3D Models with Three.js and Potree

Currently, I am working with a gltf model from this link: using Three.js and Potree. However, I am facing an issue with the model flickering. I have gone through similar posts on this topic like Flickering planes and Texture/model flickering in distance ( ...

We are hosting an event focused on DOM text selection outside of Input or TextArea elements

I need help finding a Javascript event that triggers when a user highlights paragraph text with their mouse on a web page. Once the text is highlighted, I want to access it using window.getSelection(). Just to clarify, I am not looking for ways to capture ...