简体   繁体   English

在这种情况下,如何在jquery中实现限制字符?

[英]How can I achieve a limit character in jquery in this situation?

Run the code to see result, it will replace space with '-'. 运行代码以查看结果,它将用'-'替换空格。 I want to achieve only one'-' between two text, like 'good-day', but not good----day. 我只想在两个文字之间取得一个'-',例如'good-day',但不是good-day。 Therefore, I want to know how to limit only one between word in jquery. 因此,我想知道如何在jquery中的单词之间仅限制一个。

 $('#tag').on("keydown",function(event){ var $input = $('#tag'); $input.val(function(_,v){ return v.replace(/\\s+/g,'-'); });// '-'repace space }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="tag" /> 

It is because when you enter a space it is replaced with - , then when you enter another space, (the previous one is already replaced with - ) so you have -<space> now the new space is again replaced with - so you get -- 这是因为当您输入一个空格时,它会被替换为- ,然后当您输入另一个空格时(先前的空格已经被替换为- ),因此您有了-<space> ,新的空格又被替换为-所以您得到--

 $('#tag').on("keydown", function(event) { $(this).val(function(_, v) { return v.replace(/[\\s-]+/g, '-'); }); // '-'repace space }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="tag" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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