18

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?

4
  • You're trying to match or to replace? Commented Feb 12, 2014 at 8:12
  • @sp00m i am just trying to match.. Commented Feb 12, 2014 at 8:14
  • @MichalBrašna i want to allow the user to have one space in between. Commented Feb 12, 2014 at 8:15
  • should a b c be matched ? Commented Feb 12, 2014 at 8:25

8 Answers 8

27

To match, what you need, you can use

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

Maybe you could shorten that a bit, but it matches _ as well

var re = /^(\w+\s)*\w+$/;
Sign up to request clarification or add additional context in comments.

3 Comments

I prefer this solution because it also allows single-letter matches.
@falsetru And that was the point as OP had ([a-zA-Z0-9]+\s?)* in regex
This perfectly worked!
18
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.

6 Comments

@coderman, I updated the answer. Previous answer matches only two words strings.
it is returning false for a valid "testing" input.
@coderman, It returns true for me. Maybe you're using older answer?
@coderman ya that should be test[space]ing and so ur answer will work fine.
@Ranjit, Remove ^, and $. (Slashes are parts of regular expression literal in javascript, also remove that.) And replace \ with \\ . For more information, please post a separated question.
|
6

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

1 Comment

If this is what you want, it can be simpler: ^[A-Za-z]+( [A-Za-z]+)*$
1

Working code- Inside my name.addTextChangedListener():

public void onTextChanged(CharSequence s, int start, int before, int count) {
            String n = name.getText().toString();
            if (n.equals(""))
                name.setError("Name required");
            else if (!n.matches("[\\p{Alpha}\\s]*\\b") | n.matches(".*\\s{2}.*") | n.matches("\\s.*")) {
                if (n.matches("\\s.*"))
                    name.setError("Name cannot begin with a space");
                else if (n.matches(".*\\s{2}.*"))
                    name.setError("Multiple spaces between texts");
                else if (n.matches(".*\\s"))
                    name.setError("Blank space at the end of text");
                else
                    name.setError("Non-alphabetic character entered");
            }
        }

You could try adapting this to your code.

Comments

0
var f=function(t){return Math.pow(t.split(' ').length,2)/t.trim().split(' ').length==2}

f("a a")
true
f("a a ")
false
f("a  a")
false
f(" a a")
false
f("a a a")
false

1 Comment

Does it even work? This looks like its missing a closing parenthesis.
0

Here is a solution without regular expression. Add this script inside document.ready function it will work.

var i=0;
        jQuery("input,textarea").on('keypress',function(e){
            //alert();
            if(jQuery(this).val().length < 1){
                if(e.which == 32){
                    //alert(e.which);
                return false;
                }   
            }
            else {
            if(e.which == 32){
                if(i != 0){
                return false;
                }
                i++;
            }
            else{
                i=0;
            }
            }
        });

Comments

0
const handleChangeText = text => {
    let lastLetter = text[text.length - 1];
    let secondLastLetter = text[text.length - 2];
    if (lastLetter === ' ' && secondLastLetter === ' ') {
      return;
    }
    setInputText(text.trim());
  };

2 Comments

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
Welcome to StackOverflow! Please explain your solution.
-1

use this

^([A-Za-z]{5,}|[\s]{1}[A-Za-z]{1,})*$

Demo:-https://regex101.com/r/3HP7hl/2

2 Comments

Welcome to Stack Overflow! Please read How to Answer. Why should I, or anyone else for that matter, "use this"? Instead of adding such non-sentences, please edit the question to explain why this regex does what the OP wants to do. Always remember you are not only answering to the OP, but also to any future readers (such as yourself, given this question is 6 years old)
The silly {1} is a dead giveaway, this is a stark regex beginner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.