How To Read Editor Text Before Cursor Position To Match Specific Words?
I am trying to detect when the cursor has moved somewhere immediately after a specific strings ... I can do it only for I have one string , But when I have more than one I cant't m
Solution 1:
You could use a regular expression for matching one of several words:
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!!!");
Here is a working snippet:
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>
Post a Comment for "How To Read Editor Text Before Cursor Position To Match Specific Words?"