Reputation: 87
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 matched ... If I have one string like : "color:" then the code to match the word is :
<!-- 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>
But when I have array of strings like (var array=["one","three","five"]) and I want to match any word in this array I can't do it ... so any body can help I try a lot and failed
NOTE : the code above I take it from : here
Upvotes: 3
Views: 1037
Reputation: 351278
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>
Upvotes: 3