Question

I am currently using a html5 text editor (bootstrap-wysihtml5). I'm trying to use a "keypress" event (on tab) to select specific words within the text editor.

Here is an example of my text:

<div>
  My name is {{name}} and I enjoy {{programming in Rails}}.
</div>

<div>
  {{Friend Name}} suggested that we get in touch to {{catch up}}. 
  He spoke {{highly}} about you and said that we should {{get together sometime}}. 
</div>

Goal: on 'keypress' tab event, highlight each word within {{ }}. i.e. 1. Press tab once, will highlight {{name}}. 2. Press tab on the 2nd time, will highlight {{programming in Rails}}, & so on.

Here is what I have implemented so far:

$('#wysihtml5').each(function(i, elem) {
  $(elem).wysihtml5({
    "font-styles": true,
    "events": {
      "focus": function() {
        $('.wysihtml5-sandbox').contents().find('body').on("keydown",function(event) {          
          event.preventDefault(); 

          var numLoops = _.size($(this).children());            
          var keyCode = event.keyCode || event.which;              
          if (keyCode == 9){
            // loop thru all children divs

            for (var i = 0; i < numLoops; i++) {
              // get array of all matched items {{}}  

              var sentence = $($(this).children()[i]).html();
              var toSwap = sentence.match(/\{{(.*?)\}}/g);
              var numSwap = _.size(toSwap);
              // NEED TO FIGURE OUT: How to select matched item..and move to the next one on tab           
            }                         
          }      
       });                               
      }
    } 
  }); 
}); 

Any thoughts? I've been spending 2 days on finding how to make this work. The following are the references for what I have looked at:

Was it helpful?

Solution

What you want is the index of the Regex matches.

If you perform the Regex as follows:

var reg = /\{{(.*?)\}}/g; // The Regex selector

while(match=reg.exec(sentence)) { // Iterate all the matched strings

    // match.index gives the starting position of the matched string
    // match.length gives the length of the matched string, number of characters

}

You will get the position and length of all the matches which can be used for selection. The while loop iterates all the matches.

Save the matches and user their index and length values to select them one by one.

Edit Back again. As you probably have experienced, selecting text in javascript is not the easiest task but it is completely doable.

I put together a small JSFiddle to demonstrate the technique I used to get the correct result. You can find it here. I hope it's kind of clear and I tried to comment it well.

Of course, if you have any question, just ask!

Cheers!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top