本文介绍了从contentEditable div获取最后输入的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div标签,其contenteditable设置为true。
我试图找出div中最后输入的单词。

I have a div tag with contenteditable set to true.I am trying to find out the last entered word in the div.

例如,如果我键入,这是一个测试,我打了一个空格,我希望能够得到单词 test

For example, if I type in This is a test and I hit a space, I want to be able to get the word test

我希望能够使用这种逻辑,以便我可以测试每个键入的单词(在按下空格后)。

I want to be able to use this logic so that I can test each word being typed (after the space is pressed).

如果有人可以提供帮助,那就太好了

It would be great if someone could help me with this.

推荐答案

一个简单的解决方案是以下

An easy solution would be the following

var str = "This is a test "; // Content of the div
var lastWord = str.substr(str.trim().lastIndexOf(" ")+1);

修剪可能需要用于旧版浏览器的填充程序。 ( .replace(/ \s $ /,))

trim might need a shim for older browsers. (.replace(/\s$/,""))

要删除标点符号,例如测试!!!! 您还可以像下面这样进行替换:

To strip punctuation like " Test!!! " you could additionally do a replace like following:

lastWord.replace(/[\W]/g,"");

与相比,您可能想对要忽略的字符进行更具体的定义\W ,具体取决于您的需求。

You might want to do a more specific definition of the characters to omit than \W, depending on your needs.

如果您还想在标点符号上触发事件处理程序,而不仅仅是在空格上,则最后一个不需要替换。

If you want to trigger your eventhandler also on punctuation characters and not only on space, the last replace is not needed.

这篇关于从contentEditable div获取最后输入的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 11:00