Using JavaScript to validate specific characters through a regular expression pattern

I am looking to validate a string while making sure it does not contain certain characters.

<,>,:,","/,\,|,?,*,#

My goal is to accomplish this using JavaScript. I attempted to do so with the following code.

var reg = /[^a-zA-Z0-9 \-_]+/;
reg.test(filename[0])

However, I encountered an issue with validating the symbol #.

Your assistance on this matter would be greatly appreciated.

Answer №1

Your issue arises from including the hyphen within the pattern without escaping it. This signals to the engine that you are setting a range, such as from space to underscore. It's more convenient (in my perspective) to position the hyphen either at the beginning or end of the pattern, eliminating the need for an escape character. (If working with a negated character class, it would be the second character.)

For example:

var reg = /[^a-zA-Z0-9 \-_]+/;

--OR--

var reg = /[^a-zA-Z0-9 _-]+/;

--OR--

var reg = /[^-a-zA-Z0-9 _]+/;

Answer №2

Are you looking to restrict input to English letters a-z (both lowercase and uppercase), numbers, spaces, '_', and '-'? Keep in mind that allowing these specific characters is different from disallowing others like '☃' which might not fall within the set of characters you specified but could still be invalid for your intended use case.

If you indeed only want to permit the English alphabet, numbers, spaces, '_', and '-', you can implement the following RegExp pattern along with a conditional check:

var reg = /^[a-zA-Z0-9 \-_]+$/; 
if (reg.test(inputString)) {
  // String is acceptable
}

This regular expression ensures that all characters in the string are one or more occurrences of the allowed characters within the defined range.

To specifically disallow the characters mentioned in your query, you can utilize the following approach:

var reg = /[\<\>\:\,\/\\\|\?\*\#]/; 
if (!reg.test(inputString)) {
  // The string meets requirements
} 

This code snippet searches for any of the listed characters (each escaped with a \) and deems the string invalid if any are found. Therefore, the string is considered valid only if the test fails, indicated by the presence of ! before the test.

Answer №3

let inputText ="example text" ;
const outputText = inputText.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');

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

Using Google-Prettify with AngularJS

I have been attempting to implement Google Prettify in my AngularJS project. It seems to be functioning correctly on the main page, but once I navigate to another route using Angular (after ng-view), it stops working properly. You can check out the plunker ...

Warning: npm is resolving peer dependency conflicts during the installation process

Upon running npm install for my React application, I encountered the following warnings in the logs. Despite that, the npm installation completed successfully and the dependencies were added under node_modules. My app even starts up without any issues. I ...

Establish individual states for every dynamically created component using the same handler function

I have a component in React built with Material UI, where the child component (Paper) is dynamically generated depending on the number of items in an array. The challenge I'm facing is changing the elevation property of the Paper component when it&ap ...

Is there a JavaScript/jQuery timer for re-invoking a method?

Currently, I am developing a basic animation with jQuery that utilizes the hover method. The issue arises when a user hovers over the same image twice, causing the method to be re-invoked. Any recommendations on how to implement a "timer" to prevent the ...

Lost item phenomenon: conceal information below until it emerges

I'm attempting to create a garage door effect on my website, where upon loading the page, a garage door is displayed. Upon hovering over the door, it lifts up to reveal the content behind it. The challenge I'm facing is keeping the content hidden ...

Using the OR operator in a JSON server

One way to retrieve data from a json-server (simulated server) is by using the following call: http://localhost:3000/posts?title_like=head&comments_like=today When this call is made, records will be returned where the title is similar to "head" AND c ...

Determine the total of values that are added dynamically using vuejs

When a specific option is selected in the first column of the last row, I am dynamically adding a new row to a table that includes selects and inputs. This functionality can be seen at https://jsfiddle.net/zgykgery/. When 'Service' is selected, ...

Loading JavaScript asynchronously using ExtJS

I have created a custom widget using the ExtJS framework. In order to load the necessary ext-all.js script asynchronously, I wrote an embedd.js script that also combines other JavaScript files. I've attached a function to be called when Ext.onReady is ...

Searching and adding new elements to a sorted array of objects using binary insertion algorithm

I'm currently working on implementing a method to insert an object into a sorted array using binary search to determine the correct index for the new object. You can view the code on codesanbox The array I have is sorted using the following comparis ...

Attaching this to the event listener in React JS

After delving into a beginner's guide on React JS, I encountered a slight hiccup. The issue revolves around a simple problem within the button element; specifically, an event handler that requires passing an argument. This handler serves the purpose o ...

Utilize jQuery to extract URL parameters and incorporate them into a script

I have a unique link: http://mywebsite.org/product/page?var_one=result1&var_two=result2&var_three=result3&var_four=result4 The values can vary, meaning the parameters are not fixed. My example includes 4 parameters, but there could be more ...

Reset additional javascript functions upon completion of loading a page using ajax pagination

Hi there! I'm completely new to this, and I need help with loading other plugins and allowing separate scripts to work after loading an ajax generated page. Here is my current code: jQuery(document).ready(function($) { var $mainContent = $("load-cont ...

Adjust the zoom level when a location is detected using Mapbox

I have been reading through the leaflet documentation and it mentions using the maxZoom option for location, but I am having trouble getting it to work (http://leafletjs.com/reference.html#map-locate-options). Whenever a user uses geolocation on my websi ...

Turning Geometries into Clickable Hyperlinks in Three.js with WebGl Renderer

Recently, I've been experimenting with creating a spherical 360 panorama using three.js. My goal is to incorporate clickable objects that act as hyperlinks. Despite my efforts and research on raycasting, I haven't been successful in making the ob ...

Execute JavaScript script once when route changes

I'm currently working on a system where I want to ensure that my animation-based JavaScript code only runs once after the route changes. The issue I'm facing is that when switching between pages and returning to the about page, the scripts are ca ...

The function provided to the ".run" method did not resolve to a promise

Understanding the error and its reasons, I feel that my particular scenario falls outside the norm. I am implementing Word.run() within another promise structure like this: return new Promise((resolve, reject) => { window.Word.run(context => { ...

"Dynamic value changes in bootstrap multiselect dropdowns triggered by selection in another multiselect dropdown

I am trying to enhance the functionality of my multiselect dropdown in Bootstrap by updating the values based on another multiselect selection. Currently, the code works well with one selection, but as soon as I include the class="selectpicker", ...

PhpStorm 2019.2 introduces Material UI components that have optional props instead of being mandatory

My PhpStorm 2019.2 keeps showing me a notification that the Button component from Material UI needs to have an added href prop because it is required. However, when I refer to the Material UI API, I see something different. Take a look at this screenshot: ...

Exploring ways to loop through values within nested objects

const schoolArr = { class10: { studentInfo: {name: 'John'}, exam: {result: 'pass'} }, class11: { studentInfo: {name: 'Alis'}, exam: {result: 'pass'} ...

angularJS editable input field with click-to-exit functionality

One issue I encountered involved an editable text field directive in Angular, which is structured like this: myApp.directive('editable', function () { return { restrict: 'E', scope: { model: '=&apos ...