Avoid matching if a character is found in JavaScript

For my current project, I am attempting to verify if an input field contains a valid "slug." A slug is a string that can only consist of lowercase letters and dashes, typically used in URLs.

An issue I encountered is that a user can enter a valid slug initially, but then follow it with invalid characters. Surprisingly, the regex still returns a match in this scenario.

The regular expression I'm using looks like this: /[a-z\-]+/

It correctly matches: 'my-slug-is-valid'

However, it incorrectly matches: 'my-SLUG-is not valid'

Even though the invalid characters are present after the valid portion, the regex still returns true.

var re = /[a-z\-]+/,
    str = 'my-SLUG-is not valid';

if (re.test(str) && str !== '') {
    console.log('Valid');
}

I am wondering if there is a way to modify the regex to return false when encountering characters outside of the defined character-class?

Answer №1

It seems that you are attempting to match the entire string. If that is the case, make sure to include anchors in the regex pattern:

re = /^[a-z\-]+$/

Answer №2

const regex = /^[a-z-]+$/;

Make sure to utilize the ^ and $ symbols for string anchoring purposes.

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

altering the color of various spans consecutively

I am looking to create a text effect where each alphabet changes color in a wave-like pattern, starting from the left. I have assigned each alphabet a span with classes like span0, span1, and so on. To change the color, I used the following code: for (var ...

Incorporating CouchDB storage into a Node.js socket.io JSON data stream

Currently in the process of researching how to implement persistence for a real-time Twitter JSON feed in Node.js. The stream is set up and sending data to the client, but I'm struggling with storing this information in a CouchDB database so that it c ...

What is the best way to create a form that includes both dynamic objects and dynamic arrays using a JSON schema?

I have observed how a JSON schema can be utilized to construct dynamic arrays. My goal is to develop a JSON web form using a JSON schema that allows for objects (dictionaries) to be expandable similar to arrays. For example, you can visit the demonstrati ...

Encountered a TypeError in React 16.7: The function (0, _react.useState) is not recognized

Error: TypeError: (0 , _react.useState) is not a function React versions currently being used: "react": "^16.7", "react-dom": "^16.7", File src/App.js: import {memo, useState} from 'react' export default memo(() => { useS ...

Is it possible to use Node.js without resorting to template engines

Recently, I embarked on a journey to explore the world of backend development, focusing my attention on Node.js. As I delved into Express.js and familiarized myself with routing, a curious thought crossed my mind. Is there a method to transmit data direc ...

Unable to modify background color in base website

While working on my project with Next.js, I encountered an issue where creating a button to change the color only affected the base web components' color and not the background color. _app.tsx import '../styles/globals.css'; import type { Ap ...

Form submission button gets stuck after AJAX request is made

Hey there, I'm currently working on a form that utilizes Ajax for making a post in Rails 4. The JavaScript in the form includes some validation checks and is supposed to display an alert message upon successful posting. However, I'm facing an iss ...

Expanding file input fields in Javascript

I am facing an issue with my form and file input. I need to select images from a different folder. echo '<pre>'; var_dump($_FILES); echo '</pre>'; Upon submitting the form, only the last selected image is displayed, but I ...

Is there a method to redirect the entire webpage using a script within an iframe?

I am seeking a solution to redirect the entire window to another page when clicking a link inside an iframe. It is important that it redirects the entire window, not just the iframe itself. Is this even possible? I would prefer to implement this in JavaSc ...

Utilizing async parallel for executing multiple queries

Hey there, I'm new to Javascript and I've been trying to work with the async.parallel function. I have a specific task where I am fetching data from my database and storing it in an array called "reviewArr." Then, I want to return this array of ...

Building a custom Vuetify extension to enhance core features

I am currently working on developing a plugin-based component library to ensure consistency across various product lines using vuetify. However, when I try to install the library and add the components, I encounter multiple errors related to the dark theme ...

selenium-webdriver causing issues on a nodejs server

Encountering an error while trying to start the nodejs server with selenium webdriver ubuntu@ip-10-10-10-193:~/testenvoy$ node app.js /home/ubuntu/testenvoy/node_modules/selenium-webdriver/index.js:115 static createSession(...args) {} ...

Utilizing MVC2 Devexpress Gridview: Activating a Clientside Javascript function following data binding

Is there a way to execute a Javascript function after the data binding process has finished? I attempted using EndCallback, however, it does not seem to work when the Grid is initially loaded since I am using RenderAction to show the partialview that cont ...

How to work with a JSON object in Internet Explorer 6

Looking for some quick answers that should be easy for someone with expertise to provide. I have a basic asp.net site that relies on JSON for various tasks (and JSON.stringify). Everything works fine in Firefox and the like, but in IE6 I'm getting a ...

Is it possible to arrange a react map based on the length of strings?

I am working on a React function that loops through an object and creates buttons with text strings retrieved from the map. I want to display the text strings in order of their length. Below is the code snippet for the function that generates the buttons: ...

Update a Div, Table, or TR element without the need for a page reload or Ajax usage

How can I refresh a div, table or <tr>? The data displayed is not coming from a database, it's just a simple error block and the value comes from Java-script. The issue arises when a user inputs a value in a textbox, the value gets stored in th ...

Upon sending an HTTP POST request from JavaScript to a Node server, the body was found to be

Trying to make an XMLHttpRequest from JavaScript to my node server. This is the request I am sending: var data = { "fname": "Fasal", "lname": "Rahman" }; var body = JSON.stringify(data); var xhttp = new XMLHttpRequest(); xhttp.open("POST", "/admin"); xhtt ...

Closing md-tooltip automatically after a specified timeout period

I've set up md-chips in Angular material with the following configuration: <md-chips md-chips-disable-input ng-model="session.participants"> <!-- Chip removal button template --> <button md-chip-remove class ...

Error: Cannot set value on a property that is designated as a getter-only in Vue.js using

My current task involves taking an image as input, converting it into a base64 string, preparing a payload containing the base64 string, and sending a post request to the backend. I then need to retrieve the response data and preview the base64 image from ...

Is it necessary for parameter assertion in Javascript to throw an error immediately if the function returns a Promise

I've been immersed in the world of NodeJS code for quite some time now, observing various techniques employed by different developers. One question that has been on my mind is whether it's considered a best practice to have a function that, with ...