简体   繁体   English

正则表达式强制第一个字符后的单个空格

[英]Regular expression to force single blank space after a first character

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. 在第一个字符和空格之后,最多可以有40个字符。

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 样品

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");

Do you need the regex? 您需要正则表达式吗?

$('.singleSpace').keyup(function() {
  var $el = $(this);
  var val = $el.val();
  if (val.length === 1) {
    $el.val(val + ' ');
  }
});

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/ 自己看看: 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 编辑1

Remove the authorisation to write space after the first one. 删除第一个之后的写空间授权。


Edit 2 编辑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 小提琴

The var is done to deal with the cursor position 完成var处理光标位置

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 这是您想要的regExp: *(.) *(.*?)并且您想使用.replace不匹配

Demo 演示

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

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