按退格键时从textarea中删除整个单词

时间:2014-06-30 16:44:07

标签: javascript jquery

我试图在文本区域按退格键时删除整个单词,同时按退格键,它应该检查当前单词以及另外一个单词包含@,如果找到此匹配,则删除它应该删除其他单词应该删除默认退格所做的字母。

在我的例子中,当使用退格键删除文本时,它应该在一次按键中删除单词user和@test

以下是我的例子:

 <textarea id="editabletxt">Hello @test user how are you</textarea>

 $('#editabletxt').keyup(function (e) {
  if (e.keyCode == 8) {
    e.preventDefault();
    var text = $(this).val().split(' ');
    text.splice(text.length-1); 
    $(this).val(text.join(' '));
  }
})

小提琴:http://jsfiddle.net/n7ZWc/

1 个答案:

答案 0 :(得分:1)

我们需要类似的功能,并提出以下解决方案,

$.fn.getCursorPosition = function() {
    var el = $(this).get(0);
    var pos = 0;
    var posEnd = 0;
    if('selectionStart' in el) {
        pos = el.selectionStart;
        posEnd = el.selectionEnd;
    } else if('selection' in document) {
        el.focus();
        var Sel = document.selection.createRange();
        var SelLength = document.selection.createRange().text.length;
        Sel.moveStart('character', -el.value.length);
        pos = Sel.text.length - SelLength;
        posEnd = Sel.text.length;
    }
    return [pos, posEnd];
};

$.fn.setCursorPosition = function(start, end) {
		$(this).prop("selectionStart", start);
    $(this).prop("selectionEnd", end);
}

$('#text').keydown(function (e) {
    var position = $(this).getCursorPosition();
    var deleted = '';
    var val = $(this).val();
    if (e.which != 8) {
		return true;
    }

    if (position[0] != position[1]) {
		return true;
    }

    if (position[0] <= 0) {
		return true;
    }

    let charToDelete = val.substr(position[0] - 1, 1);
    if ( charToDelete == " " ) {
		return true;
    }

    let nextChar = val.substr(position[0], 1);

    if ( nextChar == " " || nextChar == "" ) {
        start = position[0];
        end = position[0];

        while(val.substr(start - 1, 1) != " " && start - 1 >= 0) {
            start -= 1; 
        }

        e.preventDefault();

        $(this).setCursorPosition(start, end);
        //let newString = val.slice(0, start) + val.slice(end, val.length);
        //$(this).val(newString);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text">Hello @test user how are you</textarea><br />