asimes
asimes

Reputation: 5894

JavaScript regex replace as alphanumeric with spaces only between character groups

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.

Upvotes: 2

Views: 229

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208465

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.

Upvotes: 2

Related Questions