我正在尝试检测光标在特定字符串后立即移动的位置...我只能因为我有一个字符串才能做到这一点但是当我有多个时我不能匹配......如果我有一个字符串,如:" color:"然后匹配单词的代码是:
<!-- 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 = [&#34; one&#34;,&#34; three&#34;,&#34; five&#34;])并且我想匹配任何字符串在这个数组中我不能这样做......所以任何身体都可以帮助我尝试很多而且失败了
注意:上面的代码我来自:here
答案 0 :(得分:1)
您可以使用正则表达式匹配多个单词之一:
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>