使用计算机键盘按字词而不是字符删除

时间:2016-02-04 02:11:19

标签: javascript jquery html css web

我的网站上有一个textarea。我有一句话:

(e.g.)
    sampleword

我想通过单词而不是字符删除单词。

Output:
    ''
Incorrect Output:
    ampleword

更新1:

以下是我的textarea的图片:

enter image description here

我想使用键盘上的Delete按钮删除整个单词。

输出错误:

enter image description here

正确输出:

enter image description here

我该怎么做?我应该使用什么技术?

3 个答案:

答案 0 :(得分:-1)

您可以使用String.replace()

如示例中所示:

var str = 'Twas the night before Xmas...';
var newstr = str.replace(/xmas/i, 'Christmas');
console.log(newstr);  // Twas the night before Christmas...

所以你可以这样做:

var str = 'sampleword';
var newstr = str.replace('sampleword', '');

获得预期的输出。

答案 1 :(得分:-1)

这一直对我有用。

尝试以下方法:

var string = 'This is a word.';
var replacedstring = string.replace('word', 'sentence');
alert(replacedstring);

在示例中,我使用string.replace('word', 'sentence');替换单词。

在字符串This is a word.中,单词将被sentence替换。

对于jquery使用此:

$("#string").val($("#stript").val().replace('word', 'sentence'));

答案 2 :(得分:-1)

你绝对不需要jQuery来实现这一目标。常规JavaScript也足够了: https://jsfiddle.net/ot1jx61d/

var txtStr = document.getElementById("txtArea").value;
txtStr = txtStr.replace('sampleword', '');
document.getElementById("txtArea").innerHTML = txtStr;

甚至......

document.getElementById("txtArea").innerHTML = document.getElementById("txtArea").value.replace('sampleword', '');

在jQuery中: https://jsfiddle.net/9pwnm6rb/1/

$("#txtArea").val($("#txtArea").val().replace('sampleword', ''));