gpt4 book ai didi

javascript - 如何阅读光标位置之前的编辑器文本以匹配特定单词?

转载 作者:行者123 更新时间:2023-11-30 00:02:23 24 4
gpt4 key购买 nike

我试图检测光标何时在特定字符串之后立即移动到某处......我只能因为我有一个字符串才能做到这一点,但是当我有多个字符串时我无法匹配......如果我有一个字符串,如:“颜色:”,那么匹配该词的代码是:

<!-- Create a simple CodeMirror instance -->
<link rel="stylesheet" href="lib/codemirror.css">
<script src="lib/codemirror.js"></script>
<textarea id="myTextarea"></textarea>
<script>

var editor = CodeMirror.fromTextArea(myTextarea, {
lineNumbers: true
});

//Catch cursor change event
editor.on('cursorActivity',function(e){
var line = e.doc.getCursor().line, //Cursor line
ch = e.doc.getCursor().ch, //Cursor character
stringToMatch = "color:",
n = stringToMatch.length,
stringToTest = e.doc.getLine(line).substr(Math.max(ch - n,0),n);

if (stringToTest == stringToMatch) console.log("SUCCESS!!!");
});

</script>

但是当我有像 (var array=["one","three","five"]) 这样的字符串数组并且我想匹配这个数组中的任何单词时我做不到......所以任何 body 可以帮助我尝试了很多但都失败了

注意:上面的代码我取自:here

最佳答案

您可以使用正则表达式来匹配几个词之一:

var line = e.doc.getCursor().line,   //Cursor line
ch = e.doc.getCursor().ch, //Cursor character
// Select all characters before cursor
stringToTest = e.doc.getLine(line).substr(0, ch),
// Array with search words: escape characters for use in regular expression:
array=["one","three","five"].map( s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') );

// Join words with OR (|) and require they match just before the cursor
// (i.e. at end of string: $)
if (stringToTest.match(new RegExp('('+array.join('|')+')$'))) console.log("SUCCESS!!!");

这是一个工作片段:

var editor = CodeMirror.fromTextArea(myTextarea, {
lineNumbers: true
});

//Catch cursor change event
editor.on('cursorActivity',function(e){
var line = e.doc.getCursor().line, //Cursor line
ch = e.doc.getCursor().ch, //Cursor character
// Select all characters before cursor
stringToTest = e.doc.getLine(line).substr(0, ch),
// Array with search words: escape characters for use in regular expression:
array=["one","three","five"]
.map( s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') );

// Join words and require they match just before the cursor
// (i.e. at end of string: $)
if (stringToTest.match(new RegExp('(' + array.join('|') + ')$')))
console.log("SUCCESS!!!");
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.19.0/codemirror.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.19.0/codemirror.js"></script>
<textarea id="myTextarea"></textarea>

关于javascript - 如何阅读光标位置之前的编辑器文本以匹配特定单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39917590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com