简体   繁体   中英

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 ?

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.

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.

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. 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:

 $(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. Plus, it's not e.key what you want to validate, it's 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM