Regular expression that allows alphanumeric characters and spaces, but does not permit spaces at the beginning or end of the

I need to create a regular expression that allows for a combination of letters, numbers, and spaces within a word, ranging in length from 3 to 50 characters, but without spaces at the beginning or end of the string. Here is the regex pattern I have come up with:

/^[^-\s]([a-z0-9]|[a-z0-9\s-]){3,50}[^-\s]+$/i

Examples of valid strings:

uma
umair
umair K

Examples of invalid strings:

 uma
u
um
umair 

The last example contains a trailing space, making it invalid.

Answer №1

^(?=.{3,50}$)[^\W_]+(?: [^\W_]+)*$
  • ^ Start the string
  • (?=.{3,50}$) Looking ahead, there should be between 3 and 50 characters before the end of the line
  • [^\W_]+ Match any word character except _ one or more times
  • (?: [^\W_]+)* Match a space followed by one or more word characters, any number of times
  • $ End the string

var r = /^(?=.{3,50}$)[^\W_]+(?: [^\W_]+)*$/
var a = [
  'uma','umair','umair K', //valid
  ' uma','u','um','umair ' //invalid
]

a.forEach(function(s){
  console.log(r.test(s) ? `Valid: ${s}` : `Invalid: ${s}`)
})

Alternatives:

^[^\W_][a-zA-Z\d ]{1,48}[^\W_]$

Answer №2

This is how a direct translation of the given requirements would appear:

!/[^a-zA-Z\d\s]/.test(str) &&
str.length >= 3 && str.length <= 50 &&
!/^\s/.test(str) &&
!/\s$/.test(str))

Is it really necessary to combine everything into a single regular expression?

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

Protecting client-side game logic operations with web application security

I've been developing a web-based game that utilizes the Canvas feature of HTML5. However, I've come to realize that there is a significant vulnerability in my system. The scoring and gameplay statistics are currently being calculated on the clien ...

Exploring ways to retrieve object properties transmitted through the Vue event global bus

My event bus is responsible for passing the socket.io object back from the main instance to the component where I need specific information, such as the socket id. However, after emitting the related event and receiving the reply in the component, I am una ...

Save the currently active index of the mySwiper element even after the page is

After clicking through the carousel, I want to be able to store the current index and slide back to it after a page refresh. Is there a way to save this value in a variable so that I can use the mySwiper.slideTo() method to return to the last index? In si ...

Error: Material-UI prop type validation failed. Please specify either children, image, src, or component prop for CardMedia component. This error occurred at

I encountered an issue while trying to utilize the CardMedia component from Material-ui. The error message received was 'Failed prop type: Material-UI: Either children, image, src, or component prop must be specified. at CardMedia'. I attempted v ...

What is the most effective way to transfer color values from one div to another?

When recreating a game similar to Mastermind, I encountered a challenge of copying color values from one div to another upon clicking a button. Despite browsing the web, I haven't found a solution for this specific situation. Below is the code I have ...

AMD module cannot be required within a registerSuite function in Intern.js

I have encountered a situation where I am trying to include some code using the require function: define(function(require) { return stuff { my_func: function() { return 1; } }; }); When I attempt to require thi ...

How can components be utilized with v-edit-dialog?

Hey there, I've been exploring the v-edit-dialog component offered by Vuetify and had a query about its implementation. Currently, I'm structuring my v-data-table in a way where I'm importing a component with props into a template slot. The ...

How can one easily retrieve the callback function arguments from outside the function?

Here is a snippet of my code: var jenkins = require('jenkins')('http://192.168.1.5:8080'); var job_name = undefined; jenkins.job.list(function doneGetting(err, list) { if (err) throw err; job_name = list[0].name; }); jenkins. ...

Posting several pictures with Protractor

In my test suite, I have a specific scenario that requires the following steps: Click on a button. Upload an image from a specified directory. Wait for 15 seconds Repeat Steps 1-3 for all images in the specified directory. I need to figure out how to up ...

Adding a THREE.js decal to a 3D model

Currently, I am utilizing THREE.js to load a collada model that portrays a terrain filled with hills. The model itself sports a repetitive grass texture. However, I am interested in incorporating decals (if that's the correct term) onto the model. Spe ...

How can the background of a div be altered when text is typed into an input field?

I need help with the following code. I want to be able to change the background color of a div with the class "target_bg" from red (default) to green every time someone enters or types text into the input field. <div class="target_bg"></div> & ...

Achieve the same functionality as the nextjs getStaticProps() function across all pages without the need to duplicate the code on each page

Is there a way to implement the functionality of the nextjs getStaticProps() function for all pages without duplicating the code on each page? I have multiple pages and a layout component. I am looking to include a global function on all pages. Is it poss ...

Error encountered while utilizing a custom third-party component within an Angular project during static analysis

Currently, I am utilizing an Angular (2+) datepicker component (link to Github) in two separate Angular projects: Angular CLI v1.0.0-beta.30, Angular v2.3 Angular CLI v1.0.0, Angular v4.0 The first project works flawlessly both during development with n ...

Displaying list values as titles in a slider

Currently, I am utilizing the bjqs slider plugin to slide some content. Apart from the next and previous buttons, there is a navigation feature that allows users to choose their desired slide using numbers. However, I want to display the slide's title ...

Display an iframe using React in multiple areas across the app with the same state

Within my React scenario, we display a BI dashboard using an iframe on the page, allowing users to interact with the frame and potentially filter the BI data. I've developed a feature that enables this iframe to expand into a full-screen dialog for en ...

Addressing Memory Leakage Issues in a Basic Node.js Application

Out of sheer curiosity and as an experiment with NodeJS, I decided to write a basic program to test the Collatz Conjecture for an incredibly high number of integers. While this concept should work fine in theory, my simple code is unexpectedly facing a mem ...

Breaking an array in JavaScript

I'm developing a pure JavaScript hangman game and facing an issue with splitting words from an array into single letters. When I split the array, I get "," for every letter. For example, when I split the word [station], it returns "s,t,a,t,i,o,n". M ...

Tips for showing a map in a concealed location: Embed the code in the appropriate location

I've come across solutions for displaying a map in a hidden div, but as a designer and not a programmer, I'm unsure of where to insert the code. The issue is detailed in this post: Click here to view. To resolve the problem, the suggestion is to ...

Is it possible to perform direct URL searches using react-router-dom?

Encountering an issue when attempting to directly copy a route, resulting in the following error: Error: Cannot Access / home Despite utilizing various methods such as browserHistory, I am unable to successfully render views when navigating with menu i ...

Is there an efficient method for matching "data-" attributes with property names in mixed case?

In my custom jQuery plugins, I utilize a base plugin class that goes beyond what the jQuery UI widget offers by handling more complex tasks. Currently, I am looking to extract values from data- attributes attached to elements and incorporate them as optio ...