1

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.

Petya petrov
  • 2,153
  • 5
  • 23
  • 35

4 Answers4

2

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.

  • Sorry, on my iPad in bed, so I didn't create a test case, but I tried the regex in regexpal.com to make sure it would match correctly. – Sasha Aickin Apr 06 '11 at 14:58
  • Oh wait, I didn't escape the forward slash in the regex; that may be the problem. Changed (although still not tested: still in bed!) – Sasha Aickin Apr 06 '11 at 14:59
2

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.

Toto
  • 89,455
  • 62
  • 89
  • 125
0

Maybe it is easier for you to use: http://codemirror.net/ and write a custom mode for your circumstance.

Billy Moon
  • 57,113
  • 24
  • 136
  • 237
0

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>"));
    });
});

jsFiddle

Jon Gauthier
  • 25,202
  • 6
  • 63
  • 69