Getting the last entered word from a contentEditable div

孤街醉人 提交于 2020-01-03 04:59:06

问题


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

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.


回答1:


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

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

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.




回答2:


This is the ultimate way:

// listen to changes (do it any way you want...)
document.querySelectorAll('div')[0].addEventListener('input', function(e) {
    console.log( getLastWord(this.textContent) );
}, false);


function getLastWord(str){
   // strip punctuations
   str = str.replace(/[\.,-\/#!$%\^&\*;:{}=\_`~()]/g,' ');
   // get the last word
   return str.trim().split(' ').reverse()[0];
}

DEMO PAGE




回答3:


You first have to know when the content is edited. Using jQuery, that can be done with

​$("div").on("keyup", function(){ /* code */ });

Then, you'll have to get the whole text and split it into words

var words = $(this).text().trim().split(' ');

And getting the last word is as complicated as getting the last element of the words array.

Here's the whole code

HTML

​<div contenteditable="true">Add text here</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

JavaScript (using jQuery)

$("div").on("keyup", function(){
    var words = $(this).text().trim().split(' '),
        lastWord = words[words.length - 1];
    console.log(lastWord);
});​​​​​​​

Demo




回答4:


You can try this to get last word from a editable div.

HTML

<div id='edit' contenteditable='true' onkeypress="getLastWord(event,this)">
  </div>    

JS

 function getLastWord(event,element){
             var keyPressed = event.which;
             if(keyPressed == 32){ //Hits Space
                 var val = element.innerText.trim();
                 val = val.replace(/(\r\n|\n|\r)/gm," ");
                 var idx = val.lastIndexOf(' ');
                 var lastWord = val.substring(idx+1);
                 console.log("Last Word " + lastWord);
             }
        }

Try this link http://jsfiddle.net/vV2mN/18/



来源:https://stackoverflow.com/questions/12917750/getting-the-last-entered-word-from-a-contenteditable-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!