我正在尝试编写一个正则表达式来删除单词开头的空格,而不是后面的空格,并且单词后面只有一个空格。
使用的RegExp:
var re = new RegExp(/^([a-zA-Z0-9]+\s?)*$/);
测试Exapmle:
1) wordX[space] - Should be allowed
2) [space] - Should not be allowed
3) WrodX[space][space]wordX - Should be allowed
4) WrodX[space][space][space]wordX - Should be allowed
5) WrodX[space][space][space][space] - Should be not be allowed
6) WrodX[space][space] - Allowed with only one space the moment another space is entered **should not be allowed**
发布于 2013-05-26 06:22:43
试试这个:
^\s*\w+(\s?$|\s{2,}\w+)+
测试用例(为清楚起见添加了):
"word" - allowed (match==true)
"word " - allowed (match==true)
"word word" - allowed (match==true)
"word word" - allowed (match==true)
" " - not allowed (match==false)
"word " - not allowed (match==false)
"word " - not allowed (match==false)
" word" - allowed (match==true)
" word" - allowed (match==true)
" word " - allowed (match==true)
" word word" - allowed (match==true)
发布于 2013-05-26 05:40:54
试试这个:
var re = /\S\s?$/;
它匹配字符串末尾最多一个空格的非空格。
顺便说一句,当你提供一个正则表达式文字时,不需要使用new RegExp
。这只在将字符串转换为RegExp时才需要。
发布于 2013-05-26 05:42:05
试试这个正则表达式
/^(\w+)(\s+)/
和你的代码:
result = inputString.replace(/^(\w+)(\s+)?/g, "$1");
https://stackoverflow.com/questions/16756507
复制