comu
comu

Reputation: 921

Modify Character or Word after typing it JavaScript

Lets say I am typing the word "hello" into a textarea. How would I, after I had typed hello, select that word I had just typed, and modify it. For example, after I typed the word hello, without hitting the space bar, recognize the word is hello, and before and after it add <b> and </b> around the word. So the ending result would be <b>hello</b> I know textarea's don't take HTML, but for the sake of argument. The only way I can think to do this is to run a function each time the user presses a key, and add the content of the textarea to an array, breaking it at the spaces. But that requires spaces, and than having to cross reference the array will take time. Is there anyway to do this easily?

Upvotes: 2

Views: 1760

Answers (2)

nnnnnn
nnnnnn

Reputation: 150030

You'll definitely have to trap each keypress if you want it to do the replacement as you type, but you don't have to test for spaces. The following worked when I tested it in IE:

$(function() {
   $("#yourtextareaidhere").keyup(function(e) {
      var updatedText = this.value.replace(
                               /(^|[^>])(hello)($|[^<])/gi, "$1<b>$2</b>$3");
      if (updatedText != this.value)
         this.value = updatedText;
   });
});

Essentially on every keypress this does a string replace to take all instances of "hello" not already surrounded by ">" and "<" (including where "hello" is at the start or end of the string), and substitute in "<b>hello</b>". If the result of the string replace is different to what was in the field (i.e., some substitution did occur) then the new value is written back to the textarea - I don't just write it back directly every time because that loses the cursor position which is annoying for the user and I'm too lazy to come up with a better workaround than this simple "if" test. (I justify this on the basis that I'm providing you with a "starting place", and leaving the rest to you.)

This approach allows for the fact that the user may not have typed the word "hello" in one go, e.g., if they made a typo and initially had "I say hllo to you" then went back and added the "e" then you (presumably) want to replace the "hello" even though it isn't at the end. Also I do a global replace so that if the user pastes in "hello hello hello" they'll all be replaced. Decide for yourself if you want a case-insensitive replacement.

If there are other words you are looking to replace too you could add them to the same regular expression if they all just need the bold tags, otherwise if each special word has its own required formatting define an array of search regexes and replacement strings and loop through them within the function.

Note that my regular expressions are a bit rusty so I won't be at all surprised if there's a nicer way to do the same thing, but I'll leave any improvements as an exercise for the reader.

Upvotes: 3

Roland Mai
Roland Mai

Reputation: 31077

You can use the JQuery.keyup function to listen for the space key press.

$("textarea").keyup(function(event)
{ 
    var c= String.fromCharCode(event.keyCode);
    var isWhiteSpace = c.match(/\s/);
});

You can use the split and join function as well to accomplish what you describe in the latter part of your question.

Edit: Here's more on this idea: http://jsfiddle.net/ingenu8/ukkwM/

<div class="formatted"></div>
<textarea class="observed"></textarea>

and the JS:

$(document).ready(function() {
    function hasHtml(str)
    {
        return str.match(/<b>.*?<\/b>/);
    }

    function formatStr(str)
    {
        var bits = str.split(/\s+/);
        var last = bits.pop();
        if(!last.match(/^\s*$/))
        {
            if(!hasHtml(last))
            {
                bits.push('<b>'+last+'</b>');
            }
        }
        return bits.join(' ');
    }

    setInterval(function() {
        var str = formatStr($('.observed').val());
        $('.formatted').html(str);
    }, 1000);
});

Upvotes: 1

Related Questions