Checking for special characters except for hyphens and forward slashes using a regular expression

I need help with a regular expression (regex) in JavaScript that checks for special characters other than hyphen and forward slash.

function containsSpecialCharacters(str){
    var regex = /[~`!#$%\^&*+=\-\[\]\';,/{}|\\":<>\?]/g;
        return regex.test(str);
  }

var result1 = containsSpecialCharacters("apple"); // false
var result2 = containsSpecialCharacters("apple-orange"); // false
var result3 = containsSpecialCharacters("apple#"); // true
var result4 = containsSpecialCharacters("/apple/orange"); // false

Answer №1

To identify ASCII special characters, you can utilize a standard regular expression which targets them all, as seen in this reference. Afterwards, simply exclude the hyphen and backslash:

/[!$%^&*()_+|~=`{}\[\]:";'<>?,.]/

If there are any other specific special characters you want to avoid, just modify the regex accordingly.

You can verify this regex pattern by using it on: https://regex101.com/r/gxYiGp/2

Answer №2

If you're looking to only include English characters, it might be simpler to identify the exceptions rather than trying to list all the acceptable characters:

/[^\w\s\\\-]/.test(myString);

However, please keep in mind that this method may not work if you need to support international characters.

Answer №3

If you want to make it appear shorter, you can simply invert it like so:

[^\s\w-]

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

organize the values based on their priority using reactjs

I'm facing a challenge involving two arrays of objects: array1 and array2. I need to display only three values from both arrays, with priority given to array1. The requirements are as follows: if array1 contains 3 elements, all three should be shown. ...

Monitoring changes to localstorage in AngularJS

How can I monitor changes to localStorage using $watch? I have created a factory to simplify setting and getting values .factory('$localstorage', ['$window', function($window) { return { set: function(key, value) { ...

Adding a character sequence to a parsed JSON object results in a literal string outcome

I have saved some currency information in the state manager of my app and here is how I am accessing it: For example, to retrieve the value of Euro against the dollar, I use the following code: JSON.parse(this.$store.state.clientSide.currencyrates).rates. ...

Is it possible to use a Wcf polling duplex service with a client that is not using Silverlight?

I've been developing an online TicTacToe game and I'm utilizing a WCF polling duplex service to make it work. However, after dedicating a whole week to research, it seems that this service is only possible for Silverlight clients. If anyone is a ...

Vertical Dragging Division of Space

I am looking to create a draggable division that separates two areas vertically, similar to the images below: https://i.sstatic.net/AC9Gt.pnghttps://i.sstatic.net/xA4cX.png I found an online example of draggable divs and customized it to suit my needs. I ...

What are the steps to implement an expression with the md-colors directive?

Using AngularJS Material, I am trying to apply md-colors="" values using an expression similar to how it is done with ng-class="". However, I have been unsuccessful in achieving this. For instance: <md-button md-colors="{background:'accent-900-0. ...

Error: Validation issues detected in field functionality

My goal is to loop through a set of text fields and check if the user has input any values. However, I'm facing an issue where even though I have provided values in the text fields, it seems like they are empty. To better illustrate my problem, I have ...

Triggering the Vuetify select/autocomplete/combobox menu to open upon focusing on it

I'm working on implementing a Vuetifyjs Autocomplete feature. My goal is to have the menu open when the user focuses on it using the tab key after entering information in a previous input field. Below is a snippet of the code I am using: <div id=" ...

collect information from text box

Is it possible to retrieve data entered into input fields that have not been submitted and display that data in another div by clicking a button? Can this task be accomplished using scripting languages? HTML <form> <div class="div1">< ...

Having trouble getting Tailwindcss to work with Next.js - what could be causing the configuration issue?

Why is tailwind not displaying correctly in my next.js project? I'm concerned that there might be a problem with my settings. In the styles folder, I have a file called tailwind.css @tailwind base; /* Write your own custom base styles here */ /* S ...

Updating CSS classes based on conditions in Angular 2

I have a view with three buttons, and initially the content of the first button is displayed. When a button is clicked, it becomes active, but on page load, the initial button does not have the active state. To set the first button as active upon page load ...

Why are new lines being added to my package.json file, and what is their purpose?

I am the maintainer of an npm package and I've noticed that there are entries being added to package.json with underscore characters. These entries include information like the package's raw URL, specifications, and locations. "_args": [ [ ...

The lightbox fails to display in IE when a synchronous ajax request is triggered

I have a piece of code that displays a lightbox with the message 'Please Wait', followed by a synchronous ajax request that removes the lightbox once it's completed. This setup works perfectly in most browsers, but in Internet Explorer, the ...

Performing a task after a process has finished

Currently, I'm working with node JavaScript and facing an issue where I need to run a new function after a loop has completed. In the code snippet provided below, // loop through objects in data, to process it represents a basic for loop iterating ove ...

Obtain the coordinates of the pixel in an image on the canvas when a mouse

I am currently working on a project that involves using canvas. I have set a picture as the background of the canvas and would like to be able to get the original pixel point when clicking in the image area. In order to achieve this, I need to convert canv ...

It is generally not recommended to begin a constructor name with a lowercase letter in jsPDF

I'm attempting to generate a PDF using React const myComponent = () => { const pdfGenerator = () => { const doc = new jsPDF(); //I also attempted: new jsPDF('landscape', 'px', 'a4', 'false'); ...

Simple method to retrieve unordered list identifiers as an array using PHP

Currently, I am working with an unordered list where I am using DB ids as the list-item ids. When the Submit button is pressed, I want to present all the ID's of my list items as an Array in PHP. I am still learning JavaScript and although there are s ...

What is the reason behind one function triggering a re-render of a component while the other does not in Next.js?

I am currently working on a Next.js web application where one of the pages contains two functions that utilize useState() to add or remove emails from an array. const [invites, setInvites] = useState([]) // other code const lmao = () => { console.lo ...

jQuery Form Not Submitting Input Value

In one of the sections on my form, I have the following code: <div id="evchoices"> <div class="choice">Start <input type="checkbox" name="start" checked></div> <div class="choice">Pause <input type="checkbox" ...

Issues with login validation in HTML when utilizing JSON and PHP

While creating a login form in HTML using JSON and PHP, I encountered an issue where the if statements in the success function were not working properly. However, the beforeSend and error functions are functioning as expected. Can someone assist me in iden ...