Using JavaScript and TypeScript to create a regular expression that meets three different conditions

I need assistance validating a specific element in an XML document using regular expressions.

<ConfigOption>value</ConfigOption>

Here are the requirements for ConfigOption:

  1. Allowed characters include letters, numbers, underscores, and spaces.
  2. The format CONFIG-XX is acceptable, where XX represents numbers.
  3. The format CONFIGNAME?config=XX is also permitted, with XX being numbers.

This is the regular expression I have so far:

(^[a-zA-Z0-9 _]*$)|(?:\??config=\d)|(^CONFIG\-\d$)

For example:

  • 'hello' should pass validation.
  • 'hello?config=20' should pass validation.
  • 'CONFIG-20' should pass validation.
  • 'hello-' should fail validation.
  • 'hello*' should fail validation.

Can someone help me correct my regular expression? Even after testing 'hello=' or 'hello*' on 'https://regex101.com/', it still matches.

Answer №1

After careful consideration, I believe this solution aligns perfectly with your specified criteria. Please share any feedback for further refinement.

An important addition lies in incorporating the lookahead (?=\W).

It is worth noting that the third condition appears to be unnecessary and redundant.

const regex = /(?=\W)(^\b[a-zA-Z0-9 _]*)|(^[a-zA-Z0-9 _]*(?:\??[Cc][Oo][Nn][Ff][Ii][Gg][=,-]\d{2}))/;
const tests = ['*HELLO', 'hello', 'hello=', 'hello*', 'hello?CONFIG-20', 'hello?CONFIG=20', 'config=20'];

for (const test of tests) {
  console.log(regex.test(test));
}

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

Tips for positioning divs on top of an image with Twitter Bootstrap

I'm having an issue with displaying an image and dividing it using bootstrap div columns. The problem is that the image is overlapping the divs, making it impossible to click or attach jQuery events to it. Here is the code I am currently using: #view ...

Having issues with my toggler functionality. I attempted to place the JavaScript CDN both at the top and bottom of the code, but unfortunately, it is still not

I recently attempted to place the JavaScript CDN at the top of my code, but unfortunately, it did not have the desired effect. My intention was to make the navigation bar on my website responsive and I utilized a toggler in the process. While the navbar di ...

I often find myself frustrated while using Next.js because the console automatically clears itself, making it difficult for me

I am facing an issue with my form in the Next.js app. Here is how it is defined: <form onSubmit = { async() => await getCertificate(id) .then(resp => resp.json()) .then(data => console.log(data)) }> Whenever there is an erro ...

Edit the settings for the dual-axis line chart's parameters

After countless hours of scouring the Internet and numerous attempts, I have come to the decision to seek help by posting my issue on this forum. I must confess, I am not the best developer. My approach usually involves finding pre-existing code that I ca ...

Any suggestions on how to secure my socket connection following user authentication in redux?

After onSubmit, userAction.login is called which then dispatches "SUCCESS_AUTHENTICATE" to set the token of the user and socket state in their respective reducers. How can I proceed to trigger socket.emit("authenticate", {token})? ...

Is it possible to redirect any web traffic using an authentication script?

Scenario: I'm currently working on a social networking project and I'm looking for a way to validate every redirect or refresh by directing the user through another script before reaching their final destination. I've considered using a &apo ...

Top tips for seamless image transitions

Currently working on a slideshow project and aiming to incorporate smooth subpixel image transitions that involve sliding and resizing, similar to the Ken Burns effect. After researching various techniques used by others, I am curious to learn which ones ...

Transfer the imageURI to a different HTML page

My mobile app, created using PhoneGap, allows users to select an image from their album. I want to pass that selected image and display it on another HTML page. Does anyone have any suggestions on how to achieve this? Below is the code snippet: selectImag ...

A valid ReactComponent must be returned in order to properly render in React. Avoid returning undefined, an array, or any other invalid object

While working on my react application, I came across an error that I have been trying to troubleshoot without any success. It seems like I must be overlooking something important that could be quite obvious. *Error: VideoDetail.render(): A valid ReactComp ...

Checking for different elements between two arrays in AngularJS can be achieved by iterating through

I am working with two arrays: $scope.blinkingBoxes=[1,3,2] In addition, I have another array named $scope.clickedBoxes where I push several values. Currently, I use the following code to determine if the arrays are identical: if(angular.equals($scope.bli ...

The Three.js OBJMTLLoader seems to have trouble loading textures from .mtl files

Having trouble with the OBJMTLLoader? While it successfully loads the model, the diffuse and specular maps are not loading. Below is the code snippet: .js file var loader = new THREE.OBJMTLLoader(); loader.load( 'models\\Stop_t ...

What is the best way to structure a hierarchy in an array or object data using Node.js?

I have the following data arrangement: [{ Country: 'USA', State: 'CA', City: 'LA', District: 'LA-1',Town: 'LA-1,LA-1a,LA_AZ_A',Area: 'Area 51'}, { Country: 'USA', State: 'CA&ap ...

Setting the default value in a Reactive form on the fly: A step-by-step guide

When creating a table using looping, I need to set the default value of my Reactive Form to `Repeat` if the loop value matches a particular character, otherwise I want it to be empty. Here is my code: typescript rDefault:string = ""; create(){ ...

The Semantic UI Tabs in Angular 4 only function properly once they have been clicked on

I have set up semantic UI tabs in my app.component.html as shown below: <div class = "ui container"> <h1>Header/h1> <hr> <div style = "background-color: rgb(194, 221, 240);" class="ui top attached tab ...

Can a TypeScript-typed wrapper for localStorage be created to handle mapped return values effectively?

Is it feasible to create a TypeScript wrapper for localStorage with a schema that outlines all the possible values stored in localStorage? Specifically, I am struggling to define the return type so that it corresponds to the appropriate type specified in t ...

How can I prevent scrolling in Angular's cdk-virtual-scroll feature?

Is there a way to use Angular's cdk-virtual-scroll to prevent the scrollbar from moving by default? I have done extensive research but have not been able to find a solution. ...

In MUI v5 React, the scroll bar vanishes from view when the drawer is open

Currently, I am working on developing a responsive drawer in React using mui v5. In the set-up, the minimum width of the drawer is defined as 600px when it expands to full width. However, an issue arises when the screen exceeds 600px - at this point, the d ...

Ways to halt a message callback?

Looking at some lines of code from a canvas sprite animation on GitHub, I am curious about how to stop the animations once the sprite has finished. window.requestAnimFrame = (function(callback) { // Function for handling animation frames return window.r ...

The value passed to the JavaScript function appears to be null, despite not actually being null

Here are the specific API functions I am using to call from JavaScript: function SuspendActionOp(barcode, owner) { //alert(barcode+" - "+num); alert(owner); if (owner == null) { alert('owner is null'); } else { $.ajax({ url: &apo ...

`In HTML, trigger blocks based on the number chosen by the user`

I am working on creating a web page where users can select the number of friends they have, and based on that input, a corresponding number of invisible boxes will be triggered. For example, if a user selects 3 friends, 3 boxes will appear for them to ente ...