[英]regex to disallow space at begining and end and allow only one space between characters
How can I reject leading space and ending space and allow only one space between characters in JavaScript ? 如何拒绝JavaScript中的前导空格和结尾空格,并在字符之间仅允许一个空格?
I tried many patterns, here is last one: 我尝试了很多模式,这是最后一个:
^[^-\s][a-zA-Z0-9_\s-]*$
But this doesn't allow space at all. 但这根本不允许空间。
I am using [a-zA-Z0-9_\\s-]
because I just want to allow English characters. 我使用[a-zA-Z0-9_\\s-]
是因为我只想允许英文字符。
Also I cannot use trim or replace. 我也不能使用修剪或替换。 I am binding keypress to input field on html and check for the pattern and if regex.test(e.key)
is false I disable the event. 我将按键绑定到html上的输入字段,并检查模式,如果regex.test(e.key)
为false,则禁用该事件。
If you want a regexp which matches valid input, rather than matching invalid input as in other answers, then: 如果您想要一个匹配有效输入的正则表达式,而不是像其他答案中那样匹配无效输入,则:
/^\S(?!.* )\S$/
\\S
is a non-space. \\S
为非空格。 The middle part is a negative lookahead ensuring there are not two spaces anywhere. 中间部分为负前瞻,确保任何地方都没有两个空格。
You just try to remove leading and trailing space? 您只是尝试删除前导和尾随空格? Try something like that: 尝试这样的事情:
str.match(/^\s+.*\s+$/g,'');
UPD: UPD:
$(document).ready(function() { $('input').on('change keyup', function(e) { var str = $(e.target).val(); var disallowed = str.match(/^\\s+.*|.*\\s+$/g); if (disallowed != null) { $('button').prop('disabled', true); } else { $('button').prop('disabled',false); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="text"> <button>add</button>
This validates the given String as you requested: 这将根据您的要求验证给定的字符串:
var wrong = " hello, my dear friend "; var right = "hello, my dear frind" function validate(s){ var validateRegEx = new RegExp(/^\\s+|\\s\\s+|\\s+$/g); return !s.match(validateRegEx); } console.log("Validation of '" + wrong + "': " + validate(wrong)); console.log("Validation of '" + right + "': " + validate(right));
/^\\s+|\\s{2,}|\\s+$/g
is what you looking for. /^\\s+|\\s{2,}|\\s+$/g
是您想要的。 Plus, it's not e.key
what you want to validate, it's this.value
. 另外,您要验证的不是e.key
,而是this.value
。
EXAMPLE: 例:
document.getElementById("test").onkeyup = function() { var str = this.value; if (/^\\s+|\\s{2,}|\\s+$/.test(str)) this.className = "not-valid"; else this.className = ""; }
.not-valid{ background-color: #FAA; } span{ color: red; display: none; } .not-valid+span{ display: inline; }
<input id="test" /><span> not valid</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.