Cursores.js
http://cursores.bitbucket.org
Cursores allows you to get and replace the token under the cursor in a
textarea, text input, or string.
It does so by trying to match separate regexes for the text on the
left side of the cursor and the text on the right. For performance
reasons, the number of characters examined on either side of the
cursor is restricted.
For example, if we match a whitespace delimited token in the string
the quick brown fo|x jumps
(where |
denotes the cursor), the token
under the cursor is fox
.
Usage
By default new instances match whitespace delimited tokens:
> var cursor = new Cursores()
You can also create an instance that matches a whitespace delimited
token that starts with a specific character:
> var cursor = Cursores.startsWith('@')
Finally, the Cursores
constructor accepts the left regex, right
regex, and maximum search window length either side of the cursor.
One can get the token under the cursor in a textarea or text input by
calling cursor.token(el)
. Alternatively, you can pass in a string
and the index of the cursor within that string:
> var split = 'The quick brown fo|x jumps'.split('|')
> var cursor = new Cursores()
> cursor.token(split.join(''), split[0].length)
{"value": "fox", "prefix": "fo", "suffix": "x"}
To replace the token under the cursor in a textarea or text input,
call cursor.replace(el, replacement)
. You can also replace the token
in a string:
> cursor.replace(split.join(''), split[0].length, 'Fantastic Mr. Fox')
"The quick brown Fantastic Mr. Fox jumps"
Browser support
Cursores supports modern browsers, including Internet Explorer 9, that
implement selectionStart
and setSelectionRange()
.
License
Cursores is licensed under Apache 2.0.