2

I do not have much experience with JavaScript regex and am unsure how to only allow an input to have alphanumeric characters with a single space between groups of these characters.

Some examples of what is desirable:

"abcde"
"ab cde"
"ab c de"

Some examples of what is undesirable:

" abcde"
"abcde "
"ab   c   de"

I realize that I could use trim() to handle the first and last cases, split(" "), and then only concatenate non-empty strings but want to know how to do this with regex.

On a side note, I am fine with using \w to represent allowable characters, "_" is not a problem.

2
  • 1
    Do you want to disallow the input (ie match only the good cases), or fix the broken ones? Commented May 22, 2014 at 20:49
  • Fix the broken ones, ideally as they are being typed Commented May 22, 2014 at 20:55

1 Answer 1

2

If you are trying to fix the bad cases, you can use something like the following:

text = text.replace(/^ +| +$|( ) +/g, "$1");

The /^ +/ will match one or more spaces at the beginning, / +$/ will match one or more spaces at the end, and /( ) +/ will match two or more spaces anywhere in the string. The capture group will be an empty string for the first two expressions but it will be a single space for ( ) + so you will replace multiple spaces with just one.

Sign up to request clarification or add additional context in comments.

2 Comments

This does work with text that has already been entered but I was hoping to do it as the text was being typed, it seems like the " +$" will not allow it, any way around this?
It just occurred to me that I cannot do this while it is being typed as someone will type a space for the next group of characters. I was able to change yours a bit to this replace(/^ +|( ) +/g, "$1") which allows one space at the end. Thank you for explaining

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.