Skip to content Skip to sidebar Skip to footer

Javascript Wrap Text With Tag

I am adding a button to tinyMCE and I want to know how to wrap text inside tags with javascript, for instance (this highlighted text gets wrapped inside [highlight][/highlight] tag

Solution 1:

You can use the setSelectionRange (mozilla/webkit) or selection.createRange (IE) methods to find the currently highlighted text inside a textarea. I put up an example on jsfiddle, but have commented out your regexp since it hangs the browser in many instances. You need to make it more restrictive, and it currently passes a lot of other things than youtube url's as well.

However, the example has a working solution how to get the currently selected text, which you can, after fixing your pattern, apply to the idPattern.exec().

idPattern = /(?:(?:[^v]+)+v.)?([^&=]{11})(?=&|$)/;
  //  var vidId = prompt("YouTube Video", "Enter the id or url for your video");var vidId;
      el = document.getElementById('texty');
      if (el.setSelectionRange) {
        var vidId = el.value.substring(el.selectionStart,el.selectionEnd);
      }
      elseif(document.selection.createRange()) {
          var vidId = document.selection.createRange().text; 
      }

   alert(vidId);

EDIT: Wrapping the highlighted text and outputting it back to the element. example

el = document.getElementById('texty');
  if (el.setSelectionRange) {

     el.value = el.value.substring(0,el.selectionStart) + "[highlight]" + el.value.substring(el.selectionStart,el.selectionEnd) + "[/highlight]" + el.value.substring(el.selectionEnd,el.value.length);

  }
  elseif(document.selection.createRange()) {
      document.selection.createRange().text = "[highlight]" + document.selection.createRange().text + "[/highlight]"; 
  }

Solution 2:

The issue was syntax errors, not properly closed brackets and some missing semi-colons, using the help of the awesome Jsfiddle's JSHint and JSLint I fixed it :

(function () {
    tinymce.create('tinymce.plugins.shoutButton', {
        init: function (ed, url) {
            ed.addButton('shout.button', {
                title: 'shout.button',
                image: 'viral.gif',
                onclick: function () {
                    window.alert("booh");
                }
            });
            createControl: function (n, cm) {
                returnnull;
            }
            getInfo: function () {
                return {
                    longname: "Shout button",
                    author: 'You !',
                    authorurl: 'http://example.com/',
                    infourl: 'http://example.com/',
                    version: "1.0"
                };
            }
        }
    });
    tinymce.PluginManager.add('shout.button', tinymce.plugins.ShoutButton);
})();

Best Regards

Post a Comment for "Javascript Wrap Text With Tag"