3 Replies Latest reply: Aug 26, 2011 8:06 PM by John Hawkinson RSS

    JavaScript To Transpose Words

    AaronKuehn Community Member

      I am trying to write a JavaScript to transpose adjacent words.

       

      I plan to use the "move" function but am having trouble getting a reference to the word under the cursor.

       

      I can find out which character I am in within the story...but don't think I should need to iterate through all of the characters in the story to determine the word number.

       

      Can someone provide some guidance on how I can determine the number of the word under the cursor?

       

      Thanks much!

        • 1. Re: JavaScript To Transpose Words
          Harbs. MVP

          app.selection[0].words[0] gives you a reference to the word.

           

          You can use story.words.previousItem(word) to get the previous one.

           

          It's probably faster to work it out based on character indexes though.

           

          Something like this:

           

          var sel = app.selection[0];

          var story = sel.parentStory;

          var curWord = sel.words[0];

          var curWordIndex = curWord.index;

          prevWord = story.characters.item(curWordIndex-2).words[0];

           

          You can then use move to move the words around, but you will probably need to deal with the spaces as well...

           

          Harbs

          • 2. Re: JavaScript To Transpose Words
            AaronKuehn Community Member

            This is sorta the track I was on.  The problem I'm seeing is that the "index" value is in terms of characters...not the words that it's expecting.  So, for example, I'm on word #170, but the index value is #978...so when it tries to operate on word #978 it doesn't exist and blows up.

            • 3. Re: JavaScript To Transpose Words
              John Hawkinson Community Member

              Yes, that is why you use characters[978].words[0] rather than words[978].