Reputation: 2213
Hello i need to colorize some text in the contentEditable div. Let's say i need to highlight +
with blue color. On keyup event i do following $textarea.html($textarea.html().replace((/-/))/g,"<span class='blue'>$1</span>")
The obvious problem that replace fires up on the same part of stirng more than once (because i have keyup event). I can use only that type of event keyup event. How to do this? Thanks
UPD*
Maybe im not clear describe my problem. Im typing '-' and then continute type - asdasdad
. The problem is keyup event fires after each letter (this is a must), so i get too much spans, because '-' is always in string.
Upvotes: 1
Views: 190
Reputation: 44
One thing you could try is a negative lookahead, something like:
$textarea.html($textarea.html().replace((/-(?!<\/span>/))/g,"<span class='blue'>$1</span>")
That matches any "-" that isn't followed by "</span>". After you have replaced a particular dash once, it shouldn't get replaced on the next keyup. It's a bit of a hack, granted, but I think it satisfies your requirements.
Upvotes: 2
Reputation: 91488
Because javascript doesn't support lookbehind assertion you can do something like:
var str = 'abc-def-xyz';
str = str.replace(/(<span class='blue'>)?-(<\/span>)?/g, function($0,$1,$2){ return $1?$0:"<span class='blue'>-</span>";});
output:
abc<span class='blue'>-</span>def<span class='blue'>-</span>xyz
even if you run it multiple times.
Upvotes: 2
Reputation: 25592
If I understood the question correctly, you want to run a certain regex replacement in a jQuery keyup
event, but only for the first time. You can use one()
for this, to have the event handler unbind after it is first called.
$(document).ready(function() {
var $textarea = ...
$('#somewhere').one('keyup', function() {
$textarea.html($textarea.html().replace('-', "<span class='blue'>-</span>"));
});
});
Upvotes: 0
Reputation: 58601
Maybe it is easier for you to use: http://codemirror.net/ and write a custom mode for your circumstance.
Upvotes: 0