Reputation: 297
I was just playing with the medium editor I found something special. while writing if you try to hit space more than once it does not work means the editor does not accept more than one space. How cool it is.
it will be cool if we implement this in textareas or contenteditable to restrict the user from entering lots of spaces.
<h2 contenteditable="true">Write here</h2>
how do i restrict user from hiting more than one space.
Upvotes: 0
Views: 977
Reputation: 86
I tried it with a textarea. You won't be able to type in more than one space when typing in characters into this textarea. Is this what you were looking for?:
function trimSpaces(event){
var content = $('#sampleText').val();
//If you need to trim all white spaces and replace with single space
//content = content.replace(/\s\s+/g, ' ');
$('#sampleText').val("");
content = content.replace(/ +/g, ' ');
$('#sampleText').val(content);
}
function validate(event){
// Donot add the character keyed into textbox before validation
event.preventDefault();
var content = $('#sampleText').val();
//which is supported by FF and keyCode by other browsers.
var x = event.which || event.keyCode;
if(x==32){
if( content[content.length -1] ==" "){
// Do nothing if previous character was a space
}else{
// Add the character into the text area if its not a space
content+=String.fromCharCode(x);
$('#sampleText').val(content);
}
}else{
// add any characters keyed in to the text area if its not a space.
content+=String.fromCharCode(x);
$('#sampleText').val(content);
}
}
<!DOCTYPE html>
<html>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<body>
<textarea name="sampleText" id="sampleText" maxlength="200" onkeypress="validate(event)" onkeyup="trimSpaces(event)"></textarea>
</body>
</html>
Upvotes: 0