简体   繁体   English

如何从JavaScript的插入位置获取最后的信息?

[英]How To Get Last Word From Caret Position In JavaScript?

I am using pure JavaScript and I want to get the last word where my current caret position is from the text string in a variable as shown in the below image, I want to get the unknown word. 我使用的是纯JavaScript,我想从变量中的文本字符串中获取当前插入符号位置的最后一个单词,如下图所示,我想获取unknown单词。

在此处输入图片说明

In C#, I used the below code concept and its working there perfectly... 在C#中,我使用了下面的代码概念,并在其中完美地工作...

private static char[] splitters = new char[] { ' ', '\n', '۔' };
int caretPosition = string.SelectionStart;
string tempLastWord = string.Substring(0, caretPosition);
string lastWord = tempLastWord.Substring(tempLastWord.LastIndexOfAny(splitters) + 1);

Now I want to do the same in the pure JavaScript as below... 现在,我想在纯JavaScript中执行以下操作...

var splitters =  [ ' ', '\n', '۔' ];
var caretPosition = document.getElementById(Desired_ID).value.slice(0, document.getElementById(Desired_ID).selectionStart).length;
var tempLastWord = document.getElementById(Desired_ID).value.substring(0, caretPosition);
var lastWord = tempLastWord.substring(tempLastWord.lastIndexOf(splitters) + 1);

But my JavaScript code is not working perfectly. 但是我的JavaScript代码无法正常运行。 Can anyone help me...??? 谁能帮我...???

var lastWord = tempLastWord.substring(tempLastWord.lastIndexOf('\n') + 1);
lastWord = lastWord.substring(lastWord.lastIndexOf(' ') + 1);
lastWord = lastWord.substring(lastWord.lastIndexOf('?') + 1);

This works. 这可行。

var lastWord = tempLastWord.substring(tempLastWord.lastIndexOf(splitters + 1));

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

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