1

How do I force a space after first character as user types. I just need only one space after first character (no spaces allowed before first one). After first character and space there can be upto 40 characters.

I found this so far, but does not fit my needs

$('.singleSpace').keyup(function() {
  var foo = $(this).val().split(" ").join(""); // remove hyphens
  if (foo.length > 0) {
    foo = foo.match(new RegExp('.{1}', 'g')).join(" ");
  }
  $(this).val(foo);
});

sample

Evan Davis
  • 35,493
  • 6
  • 50
  • 57
CoolArchTek
  • 3,729
  • 12
  • 47
  • 76

4 Answers4

1

I don't know why you want to do this but to remove spaces you can use this :

var str = $(this).val().replace(" ", "");

And for add a space after first character :

var str = $(this).replace("^(.)(.*)$", "$1 $2");
Emrys Myrooin
  • 2,179
  • 14
  • 39
0

Do you need the regex?

$('.singleSpace').keyup(function() {
  var $el = $(this);
  var val = $el.val();
  if (val.length === 1) {
    $el.val(val + ' ');
  }
});
Jivings
  • 22,834
  • 6
  • 60
  • 101
  • This will give space after first character and won't remove the spaces before first letter – Akxe Apr 24 '14 at 19:08
  • 1
    @Akxe There wont be any spaces before the first letter because the length of the value is 1. If you want to stop the user from typing spaces at all then also do a string replace. – Jivings Apr 24 '14 at 19:13
  • @Jivings What if the user keep the key down (and print 2 characters)? If he copy paste? if he had space before the character he already has entered? This cover a single of the numerous issues. – Karl-André Gagnon Apr 24 '14 at 19:30
  • @Karl-AndréGagnon Yeah, fair enough. – Jivings Apr 24 '14 at 19:38
0

You can use this code :

$('.singleSpace').keyup(function() {
    var foo = $(this).val().replace(/^( *)([^ ] *)(.*)/g, function(_,b,c,d){
        return $.trim(c) + ' ' + d.replace(/ /g, '').slice(0,40);
    })
    
    $(this).val(foo)
});

The only problem is the cursor position. If you type while the cursor is not at the end, the cursor will always return the the end.

See for yourself : http://jsfiddle.net/S3gJL/2/

I would suggest you tu put that function in a blur event instead, but that can be annoying aswell.

Your request is not simple at all. There is a lot of variation, users can copy paste, select and delete. It is hard to prevent everything.

The code provided above block a lot of detour (only thing that doesn't block is the right-click paste and maybe other things i'm not think of), but with the cost stated above. You might wanna search for a plugin or hire someone to develop a good system.


Edit 1

Remove the authorisation to write space after the first one.


Edit 2

For the cursor position here the fix :

$('.singleSpace').keyup(function() {
    var foo = this.value.replace(/^( *)([^ ] *)(.*)/g, function(a,b,c,d,e){
        return $.trim(c) + ' ' + d.replace(/ /g, '').slice(0,40);
    })
    
    var carretPos = doGetCaretPosition(this)
    
    carretPos += foo.length - this.value.length
    
    this.value = foo;
    
    setSelectionRange(this, carretPos, carretPos)
});


//Code taken from
// http://stackoverflow.com/questions/17858174/set-cursor-to-specific-position-on-specific-line-in-a-textarea
function setSelectionRange(input, selectionStart, selectionEnd) {
    if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    }
    else if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    }
}

//Code taken from
// http://stackoverflow.com/questions/2897155/get-cursor-position-in-characters-within-a-text-input-field
function doGetCaretPosition (oField) {
    
    // Initialize
    var iCaretPos = 0;
    
    // IE Support
    if (document.selection) {
        
        // Set focus on the element
        oField.focus ();
        
        // To get cursor position, get empty selection range
        var oSel = document.selection.createRange ();
        
        // Move selection start to 0 position
        oSel.moveStart ('character', -oField.value.length);
        
        // The caret position is selection length
        iCaretPos = oSel.text.length;
    }
    
    // Firefox support
    else if (oField.selectionStart || oField.selectionStart == '0')
        iCaretPos = oField.selectionStart;
    
    // Return results
    return (iCaretPos);
}

FIDDLE

Community
  • 1
  • 1
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
0

The var is done to deal with the cursor position

var val="";
$('.singleSpace').keyup(function() {
    var ele = $(this)[0];
    var foo = ele.value;
    if(val==foo){return false}
    var startPos = ele.selectionStart;
    var endPos = ele.selectionEnd;
    if(event.keyCode==8){
        var diff=endPos-startPos;
        startPos-=diff;
        endPos-=diff;
    }
    foo = foo.replace(new RegExp('( )','g'),'');
    foo = foo.replace(new RegExp('^ *(.) *(.*?)'),'$1 $2');
    val=foo;
    ele.value=foo;
    ele.selectionStart=startPos;
    ele.selectionEnd=endPos;
});

This is the regExp you want: *(.) *(.*?) and you want to use .replace not match

Demo

Akxe
  • 9,694
  • 3
  • 36
  • 71
  • I'm sorry, how does that deal with the cursor position? When i start typing in the middle of the string, my cursor goes back to the end... But hey, that's a nice regexp! Nicer than mine I think! – Karl-André Gagnon Apr 24 '14 at 19:37
  • Ah... yeah... but you can at least remove the char in middle :D will focus on that part once more – Akxe Apr 24 '14 at 19:39
  • Good job! We're 2. Only problem though, when you insert your space, your cursor is behind 1 character. See my code above to fix your! – Karl-André Gagnon Apr 24 '14 at 19:58