What is the best method to verify a string against a set of approved characters using JavaScript?

I have written some code that sanitizes user input to allow only alphanumeric characters and hyphens.

Here is the code snippet: https://jsfiddle.net/py4pnr0L/

const inputValue = 'GHJHlk;sxa787BVK';
const sanitizedValue = inputValue.toLowerCase().replace(/[^a-z0-9\-]/gi, '-');
console.log(sanitizedValue);

The above code returns: ghjhlk-sxa787bvk

Now, I am looking for a way to check if a given string contains any characters outside of the allowed range without modifying the original string. I simply need to receive a true/false result based on the input string.

I am working with ES2015, so I am open to solutions using ES2015 features for a clean implementation.

Answer №1

One way to check for certain characters in a string is by using the match method, as shown below:

string = 'HJG9865sjhdkLMN';
 
console.log(!string.match(/[^a-zA-Z0-9\-]/))

Answer №2

To check for a match between a regular expression and a specified string, you can utilize the RegExp#test() method:

This method executes a search and returns either true or false.

It is advised not to use the /g modifier with this method as it may affect the lastIndex property and lead to incorrect results. For more information, refer to this thread on erroneous results due to global flag usage in JavaScript regex.

The pattern /[^a-z0-9-]/i, which matches any character outside of a-z, A-Z, 0-9, and excluding -, can be applied here. Simply avoid including the /g flag.

var value = "GHJHlksxa787BVK";
document.body.innerHTML = /[^a-z0-9-]/i.test(value);

The /i modifier ensures case insensitivity; therefore, /[a-z]/i is equivalent to /[A-Za-z]/.

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

Find the total number of table rows that exist between two specific rows using jQuery

<table> <tr id="family_1"> <td>Family 1</td> </tr> <tr class="member"> <td>Member 1</td> </tr> <tr class="member"> <td>Member 2</td> </tr> ... <tr ...

Separating the rules for development and production modes in the webpack configuration file

I'm currently in the process of working on a front-end project using HTML. Within my project, I have integrated the Webpack module bundler and am utilizing the image-webpack-loader package for image optimization. However, I've encountered an issu ...

Display and conceal different sections using hyperlinks

Hey there, I'm back with another issue related to this code snippet on jsfiddle: https://jsfiddle.net/4qq6xnfr/9/. The problem I'm facing is that when I click on one of the 5 links in the first column, a second div appears with 3 links. Upon clic ...

Load a webpage using javascript while verifying permissions with custom headers

Seeking guidance as a novice in the world of JavaScript and web programming. My current project involves creating a configuration web page for a product using node.js, with express serving as the backend and a combination of HTML, CSS, and JavaScript for t ...

React ES6 SystemJS encountered an unforeseen token error that couldn't be caught

Even though I have imported react and react-dom using the System.config setup below, I am still encountering the error mentioned here: Uncaught (in promise) Error: Unexpected token <(…) Here is the HTML structure: <!DOCTYPE html> <html l ...

Retrieve all the records from the collection that have a specific reference number in their ID field

Is it feasible to pull together all documents with an ID that includes a specific value? I am working with Angular 7. I attempted using db.collection('items').where.. but unfortunately, this method is not supported. For instance: (collection) ...

An error occurred due to an unexpected identifier, '_classCallCheck', while the import call was expecting exactly one

Encountering an unexpected identifier '_classCallCheck'. Import call requires precisely one argument. Having trouble with React Native. I have attempted every solution found on the internet, but none proved successful. Is there any way to upgrade ...

Expanding the visual in a spacious display with the help of ng-carousel from the Bootstrap framework

I have created a slider with multiple images on a website using Angular 4. The slider is displayed in a small area of the webpage and I would like to add a feature where the user can click on an image to view it in a larger screen or window. This could i ...

Consistentize Column Titles in Uploaded Excel Spreadsheet

I have a friend who takes customer orders, and these customers are required to submit an excel sheet with specific fields such as item, description, brand, quantity, etc. However, the challenge arises when these sheets do not consistently use the same colu ...

Utilizing AngularJS: Executing directives manually

As a newcomer to AngularJS, I am facing a challenge that requires creating a 3-step workflow: The initial step involves calling a web service that provides a list of strings like ["apple", "banana", "orange"]. Upon receiving this response, I must encap ...

Implement a jQuery slider that pauses on hovering

Currently, I am grappling with the clearInterval function in a small jQuery project. To better illustrate the issue, I have created a jsFiddle example: http://jsfiddle.net/eWTSu/ While the rotation works smoothly, I encountered an obstacle when hovering ...

Are there any ways to pass an onClick function to a controller in React?

To prevent duplicate numbers from being generated, I added a button that, when clicked by a user, displays a message indicating that the value is being saved to avoid duplicates. However, when attempting to handle this on the server side controller, I enco ...

"Simultaneously updating the UpdatePanel, triggering a JavaScript postback, and modifying the querystring in a SharePoint Search

Struggling with a tricky issue here. Let me try to clarify: I have a SharePoint results page where I'm using a Search Results Core WebPart. Now, I want to modify the parameter in the querystring upon postback so that the WebPart displays different re ...

Exploring the intricacies of JSON object retrieval

I'm currently working on a form that allows users to submit address details for a selected location. However, before submitting the form, I want to give the user the ability to preview the address that will be sent. The addresses are stored within a J ...

Vue-router is failing to display child routes in the application

I have an object within the Vue router that specifies a path for books and their details. { path: "/books", name: "books", component: Books, children: [ { path: ":id", name: "books.detail", ...

Browsersync in Gulp keeps triggering numerous reloads every time a file is changed

As I utilize browsersync with Gulp for running specific tasks upon file changes, I notice that each time I save a file, my terminal displays 10+ [BS] Reloading Browsers... messages and the overall performance suffers. Below is an outline of my gulpfile: ...

When a textbox is modified and a button is clicked in ASP.NET, triggering both client-side and server-side events

I have a popup that allows users to change an address. It contains three text boxes (Address, Province, and ZIP) and one DropDownList for the City. When the ZIP code is changed, an ajax call updates the province text box. I also want to later populate the ...

Choosing JavaScript

<select> <script type="text/javascript"> $.get( 'http://www.ufilme.ro/api/load/maron_online/470', function(data){ var mydata = new Array(); var i = 0; // индекс масси ...

Is it possible to create cloud functions for Firebase using both JavaScript and TypeScript?

For my Firebase project, I have successfully deployed around 4 or 5 functions using JavaScript. However, I now wish to incorporate async-await into 2 of these functions. As such, I am considering converting these specific functions to TypeScript. My conc ...

Combine the values of two fields in real-time on a Model-View-Controller Edit form

One challenge I am facing is within an MVC Edit form that contains two fields named ExVAT and VAT. I would like to introduce a new field that displays the total of these two values. Currently, the total only reflects the sum of the two fields upon initial ...