Limit Javascript Regex to accept only one specific possibility and exclude all others

Here are the specific validations I need for my URL:

cars : valid

cars/ : valid (Accepting any number of '/' after "cars")

cars- : invalid

cars* : invalid

carsp : invalid (Rejecting any character after "cars" except '/')

**cars/new: valid

cars/old: valid (After '/', anything is accepted)**

What should be the regular expression for this?

I attempted with: cars[/]*[^-]

Unfortunately, it did not work as expected.

Answer №1

^automobiles(\/.*)?$

^...$ The text must start with, and end with (Or in other words, the text should only consist of).

automobiles automobiles

(...)? Furthermore, it could be

\/.* a slash followed by any character.

Answer №2

Seems like you're interested in the term "cars" followed by:

  • nothing
  • or any sequence starting with at least one /

To achieve this, you can use the regex pattern:

cars(\/.*)?

However, determining your precise requirements is crucial. Providing more context could clarify things further.

Answer №3

To implement a positive look-ahead assertion, follow these steps:

/^cars(?=\/).*/

This regular expression will match the word 'cars' only if it is immediately followed by a slash in the 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

Create a dynamic effect by adding space between two texts on the page

const Button = () => { const options = ['test1', 'test2', 'test3']; return ( <div style={{ position: 'absolute', left: '8px', width: 'auto', flexDirection: 'row' ...

Store live text field group in their respective index

I am working on a project that involves creating dynamic description textareas based on the value selected from a dropdown list. The dropdown list contains numbers 1 through 5, and for each number chosen, I need to generate corresponding textareas with ser ...

Do not activate hover on the children of parents using triggers

Check out my demonstration here: http://jsfiddle.net/x01heLm2/ I am trying to achieve two goals with this code. Goal number one is to have the mini thumbnail still appear when hovering over the .box element. However, I do not want the hover event to be tr ...

Rearrange the li elements within multiple ul lists using JavaScript

Is there a way to reorder multiple ul-lists on my website using JavaScript? An example of the lists may be as follows: $(document).ready(function() { var ul = $('ul.filelist'); for (let u = 0; u < ul.length; u++) { const element = ul[ ...

Executing Knex promises sequentially within a for loop

I have recently started to dive into Node and asynchronous coding, but I am struggling with a fundamental concept. I am trying to seed a database using knex, reading data from a CSV file and iterating through the rows in a for loop. In each iteration, I ne ...

Prevent links from being clicked multiple times in Rails using Coffeescript

Please make the following link inactive after it has been clicked once <%= link_to "Submit Order", {:action => "charge"}, class: 'btn btn-primary', id: 'confirmButton' %> To permanently deactivate the link, use the code below ...

Tips for formatting a phone number using regular expressions in [Vue 2]

I am currently working on creating regex code that will meet the following requirements: Only allow the first character (0th index) in a string to be either a '+' symbol or a number (0-9). No non-numerical values (0-9) should be allowed anywhere ...

Internet Explorer causing trouble with reliable Ajax dropdown selection

There are two drop-down lists on my website, where the options in one depend on the selection in the other. The Ajax code works perfectly fine in Chrome and Mozilla, but it's not functioning correctly in Internet Explorer (specifically IE9). I need so ...

Error encountered when using prisma findUnique with where clause

Trying to set up a Singup API using ExpressJS and Prisma is proving to be a bit challenging. The issue arises when I attempt to verify if a given email already exists in my database. Upon passing the email and password, an error is thrown stating Unknown ...

Counting each item with jQuery and assigning them numbers 02, 03, 04, etc., with the exception of the first item which will display as "Up Next

I'm still learning jQuery and here's the code I've put together after researching on stackoverflow and other platforms: var counter = 1; $('.next-page .nav-item').each(function () { if ($(this, ':gt(0)')) { $(this ...

Having trouble with my PHP regular expression to detect duplicated characters

Having trouble with basic php regex to identify repeated characters... $subject = 'rrrr'; var_dump(preg_match("/([a-zA-Z])\1{2,}$/i", $subject)); var_dump(preg_match("/(\w)\1{2,}$/i", $subject)); It seems to be working correctly ...

Display successive slidedown notifications consecutively

I want to implement a feature that shows slide down alerts using angularjs. Here is the code I have written: function LoginController($scope, $timeout) { $scope.alerts = [{ name: "Alert 01 something something" }, { name: &qu ...

In the world of coding, the trio of javascript, $.ajax,

I need help with iterating over an array and assigning a variable using a for loop. Here is the scenario: function Person(name, status){ this.name = name; this.status = status; } var status = []; var array = ["bill","bob","carl","ton"]; function exAj ...

Replace the content within the iFrame completely

Is it possible to have a textarea where I can input HTML code and see a live preview of the webpage in an iframe as I type? For example, here is the code I'd like to write in the textarea: <!DOCTYPE html> <html> <head> ...

The Jquery ajax page is redirecting automatically when a post request is made

Encountering an issue while attempting to upload multiple files through AJAX, as the process redirects to a blank page displaying only the names of the uploaded files. Here is the HTML tag: Below is the JavaScript function: function upload(){ var proje ...

Is there a way to retrieve the final value from an Observable?

Trying to retrieve the last value from an observable. Here is an example of the code: // RxJS v6+ import { lastValueFrom, Subject } from 'rxjs'; import { scan } from 'rxjs/operators'; async function main() { const subject = new Subje ...

The www file is only loaded by Node Inspector when the preload setting is turned off

Whenever I start node-inspector The node-inspector browser window successfully loads all the files. However, when I use node-inspector --preload=false Only my bin/www file is loaded on the node-inspector window. Oddly enough, my colleagues are not f ...

Violation of Content Security Policy directive has occurred

During my full-stack project development, I encountered an issue with the inclusion of the bundle.js file in my base HTML file using a simple script tag. When trying to render the page and utilize the JS functionality, I faced a content security policy vio ...

methods for sorting firestore data in react on client side

Fetching data from firestore and applying filters const [projects, setProjects] = useState([]); const fetchData = (sortBy = "NAME_ASC") => { const unsubscribe = firebase .firestore() .collection("projects") ...

Postback fails to trigger following JavaScript onchange event

Within my asp.NET application, I have incorporated a control that validates form input data using server-side logic. The concept is simple - drag the control to the desired location, configure it in the code behind, and watch as the form gets validated. ...