[英]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.我对 JavaScript regex 没有太多经验,我不确定如何只允许输入包含字母数字字符,这些字符组之间有一个空格。
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.我意识到我可以使用
trim()
来处理第一个和最后一个案例, split(" ")
,然后只连接非空字符串,但想知道如何使用正则表达式来做到这一点。
On a side note, I am fine with using \\w
to represent allowable characters, "_" is not a problem.附带说明一下,我可以使用
\\w
来表示允许的字符,“_”不是问题。
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.前两个表达式的捕获组将是一个空字符串,但对于
( ) +
它将是一个空格,因此您将仅用一个空格替换多个空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.