views:

234

answers:

1

Hi there

I'm using jquery to get the last word in a string, but i want to be sure it is the best way (performance wise), because the string could get very long

furthermore, i want to add capability to get the "current" word, which may not simply be the last word..

This is my code so far

 <script type="text/javascript">
  function lookup()
  {
    var s = $('#text').val().split( " " ).pop();
    if(!s.length)
      return false;

    $('#output').html('"'+s+'"');
  }
  </script>

  <div id="main">
       <textarea id="text" rows="5" cols="50" onkeyup="lookup(this.value);">
       </textarea>
       <div id="output"></div>
  </div>

any tips on how i can get it to handle more than just the "last" word, ie, if i move the cursor back a few words to another word, can i still somehow get the current position & then get that word?

A: 

Although perhaps not the absolute fastest solution, this will be faster than creating an array and popping off elements.

I always tend to use PHP's strrpos function to do such things (particularly with file extensions) so this comes pretty natural (from php.js)

// find position of last occurrence of string within variable
function strrpos (haystack, needle, offset) {
    var i = (haystack+'').lastIndexOf(needle, offset); // returns -1
    return i >= 0 ? i : false;
}

function lookup(val) {
    var pos = strrpos(val, ' ');
    if (pos == false)
        return false;

    // get substring of value from 0 to the last
    // occurrence of empty string
    val = val.substring(0, pos + 1);

    $('#output').html(val);
}
cballou