Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regexp to allow only one space in between words

I'm trying to write a regular expression to remove white spaces from just the beginning of the word, not after, and only a single space after the word.

Used RegExp:

var re = new RegExp(/^([a-zA-Z0-9]+\s?)*$/);

Test Exapmle:

1) test[space]ing - Should be allowed 
2) testing - Should be allowed 
3) [space]testing - Should not be allowed 
4) testing[space] - Should be allowed but have to trim it 
5) testing[space][space] - should be allowed but have to trim it 

Only one space should be allowed. Is it possible?

like image 339
coderman Avatar asked Feb 12 '14 08:02

coderman


People also ask

How do you restrict whitespace in regex?

Trimming Whitespace You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for ^[ \t]+ and replace with nothing to delete leading whitespace (spaces and tabs). Search for [ \t]+$ to trim trailing whitespace.

What is the regex for space?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.

What is the meaning of \b in regex?

With some variations depending on the engine, regex usually defines a word character as a letter, digit or underscore. A word boundary \bdetects a position where one side is such a character, and the other is not.

Can regex contain space?

Yes, also your regex will match if there are just spaces.


2 Answers

This one does not allow preceding and following spaces plus only one space between words. Feel free to add any special characters You want.

^([A-Za-z]+ )+[A-Za-z]+$|^[A-Za-z]+$

demo here

like image 82
Rafał Rowiński Avatar answered Oct 18 '22 08:10

Rafał Rowiński


function validate(s) {
    if (/^(\w+\s?)*\s*$/.test(s)) {
        return s.replace(/\s+$/, '');
    }
    return 'NOT ALLOWED';
}
validate('test ing')    // => 'test ing'
validate('testing')     // => 'testing'
validate(' testing')    // => 'NOT ALLOWED'
validate('testing ')    // => 'testing'
validate('testing  ')   // => 'testing'
validate('test ing  ')  // => 'test ing'

BTW, new RegExp(..) is redundant if you use regular expression literal.

like image 39
falsetru Avatar answered Oct 18 '22 07:10

falsetru