http://stackoverflow.com/questions/4652734/return-html-from-a-user-selected-text/4652824#4652824
346869
function( containerNode )
    {
        if( getSelectionCollapsed( containerNode ) )
            return null;
        if( window.getSelection )
        {
            var sel = window.getSelection();
            if( sel.rangeCount )
            {
                var container = document.createElement('div'),
                    len = sel.rangeCount;
                for( var i=0; i < len; ++i )
                {
                    var contents = sel.getRangeAt(i).cloneContents();
                    container.appendChild(contents);
                }
                return container.innerHTML;
            }
        }
        else if( document.selection )
        {
            var sel = document.selection;
            if( sel.type == 'Text' )
            {
                var range = sel.createRange();
                return range.htmlText;
            }
        }
        return null;
    }
1022212
function(htmlString) {
        var matchResult;
        htmlString = htmlString.replace(/[\n\r\t]/g, '');
        if (snippet.hasEncodableString(htmlString)) {
            if (/<img/i.test(htmlString)) {
                matchResult = htmlString.match(/<img[^>]*\ssrc=["']?([^>"']+)["']?[^>]*>/i);
                htmlString = matchResult ? matchResult[1] : '';
            } else {
                htmlString = htmlString.replace(/<button.*?<\/button>/gi, '');
            }
            htmlString = $.trim(snippet.decodeHTMLEntity(
                htmlString.replace(/<\/?(?:h[1-5]|[a-z]+(?::[a-z]+)?)[^>]*>/ig, '')
            ));
        }

        return htmlString;
    }
1293782
def textFromHTML(html):
    
    cleaner = lxml.html.clean.Cleaner(scripts=True)
    cleaned = cleaner.clean_html(html)
    return lxml.html.fromstring(cleaned).text_content()
693961
public String getHtmlCode()
	{
		Object[] _params =
		{
			SgmlUtils.generateAttribute(HtmlUtils.AttributeNames.VALUE, getValue())
		};
		MessageFormat _format = (isSelected()) ? FORMAT__SELECTED : FORMAT__NOT_SELECTED;
		return _format.format(_params);
	}
1250005
function toHTML()
    {

        return '<div class="captcha-container"><img src="' . $this->form_properties['assets_url'] . 'process.php?captcha=' . ($this->form_properties['captcha_storage'] == 'session' ? 2 : 1) . '&amp;nocache=' . time() . '" alt=""' . ($this->form_properties['doctype'] == 'xhtml' ? '/' : '') . '><a href="javascript:void(0)" title="' . $this->form_properties['language']['new_captcha'] . '">' . $this->form_properties['language']['new_captcha'] . '</a></div>';
    
    }
758951
function parseGuestWlanHTML(html)
{
    $ = cheerio.load(html);
    var form = $('form');
    var settings = {};

    $('input', form).each(function(i, elem) {
        var val;
        var name = $(elem).attr('name');
        if (!name) return;

        switch ($(elem).attr('type')) {
            case 'checkbox':
                val = $(elem).attr('checked') == 'checked';
                break;
            default:
                val = $(elem).val();
        }
        settings[name] = val;
    });

    $('select option[selected=selected]', form).each(function(i, elem) {
        var val = $(elem).val();
        var name = $(elem).parent().attr('name');
        settings[name] = val;
    });

    return settings;
}
112995
function() {

      var attrs, x, y, z, key, value, html, inputs, textarea;

      console.log(hashedit.current.node);

      if (hashedit.current.node !== null) {

        // get attributes
        attrs = hashedit.current.node.attributes;

        for (x = 0; x < attrs.length; x += 1) {

          // get key and value
          key = attrs[x].nodeName.replace(/-([a-z])/g, function(g) {
            return g[1].toUpperCase();
          });
          value = attrs[x].nodeValue;

          // if is numeric
          if (!isNaN(parseFloat(value)) && isFinite(value)) {
            value = parseFloat(value);
          }

          // set value
          inputs = document.querySelectorAll('[data-model="node.' + key + '"]');

          for (y = 0; y < inputs.length; y += 1) {
            inputs[y].value = value;
          }

        }

        // get html
        html = hashedit.current.node.innerHTML;

        // remove the element menu
        var i = html.indexOf('<span class="hashedit-element-menu"');
        html = html.substring(0, i);

        inputs = document.querySelectorAll('[data-model="node.html"]');

        for (y = 0; y < inputs.length; y += 1) {
          inputs[y].value = html;
        }


      }


    }
430880
public String prettyHtml() {
        StringBuilder html = new StringBuilder();
        for (Change aDiff : getChangeList()) {
            String text = aDiff.text.replace("&", "&amp;")
                                    .replace("<", "&lt;")
                                    .replace(">", "&gt;")
                                    .replace("\n", "&para;<br>");
            switch (aDiff.operation) {
                case INSERT:
                    html.append("<ins style=\"background:#e6ffe6;\">").append(text)
                        .append("</ins>");
                    break;
                case DELETE:
                    html.append("<del style=\"background:#ffe6e6;\">").append(text)
                        .append("</del>");
                    break;
                case EQUAL:
                    html.append("<span>").append(text).append("</span>");
                    break;
            }
        }
        return html.toString();
    }
137353
function unescapeHtml(s) {
            if (_toString.call(s) != "[object String]") return s;
            if (!s) return "";
            return s.replace(/(&lt;)|(&gt;)|(&amp;)|(&quot;)/gm, function (match) {
                switch (match) {
                    case "&lt;":
                        return "<";
                    case "&gt;":
                        return ">";
                    case "&amp;":
                        return "&";
                    case "&quot;":
                        return "\"";
                    default:
                        return match;
                }
            });
        }
1123734
function getHtmlFromMarkedMarkdown(srcStr) {
	var result = parseSource(srcStr);
	var html = md.render(result);
	return html;
}
378802
function () {
			var that = this,
					$el = $.fn.mediumInsert.insert.$el;

			$el.on('selectstart mousedown', '.mediumInsert', function (e) {
				if ($(e.target).is('img') === false) {
					e.preventDefault();
				}
			});

			$el.on('blur', function () {
				var $clone = $(this).clone(),
						cloneHtml;

				$clone.find('.mediumInsert').remove();
				cloneHtml = $clone.html().replace(/^\s+|\s+$/g, '');

				if (cloneHtml === '' || cloneHtml === '<p><br></p>') {
					$(this).addClass('medium-editor-placeholder');
				}
			});


			// Fix #29
			// Sometimes in Firefox when you hit enter, <br type="_moz"> appears instead of <p><br></p>
			// If it happens, force to wrap the <br> into a paragraph
			$el.on('keypress', function (e) {
				if (that.isFirefox) {
					if (e.keyCode === 13) {
						//wrap content text in p to avoid firefox problems
						$el.contents().each((function() {
							return function(index, field) {
								if (field.nodeName === '#text' && field.textContent.trim() !== '') {
									document.execCommand('insertHTML', false, "<p>" + field.data + "</p>");
									return field.remove();
								}
							};
						})(this));
						// Removed because of #94 issue
						//
						// Firefox add extra br tag inside p tag
						// var latestPTag = $el.find('p').last();
						// if (latestPTag.text().length > 0) {
						//   latestPTag.find('br').remove();
						// }
					}
				}
			});

			// Fix #39
			// For some reason Chrome doesn't "select-all", when the last placeholder is visible.
			// So it's needed to hide it when the user "selects all", and show it again when they presses any other key.
			$el.on('keydown', function (e) {
				// Fix Select-all using (ctrl + a) in chrome
				if (navigator.userAgent.match(/chrome/i)) {
					$el.children().last().removeClass('hide');
					if ( (e.ctrlKey || e.metaKey) && e.which === 65) {
						e.preventDefault();
						if($el.find('p').text().trim().length === 0) {
							return false;
						}

						$el.children().last().addClass('hide');
						return document.execCommand('selectAll', false, null);
					}
				}
			});

			$el.on('click', '.mediumInsert-buttons a.mediumInsert-buttonsShow', function () {
				var $options = $(this).siblings('.mediumInsert-buttonsOptions'),
						$placeholder = $(this).parent().siblings('.mediumInsert-placeholder');

				if ($(this).hasClass('active')) {
					$(this).removeClass('active');
					$options.hide();

					$('a', $options).show();
				} else {
					$(this).addClass('active');
					$options.show();

					$('a', $options).each(function () {
						var aClass = $(this).attr('class').split('action-')[1],
								plugin = aClass.split('-')[0];
						if ($('.mediumInsert-'+ plugin, $placeholder).length > 0) {
							$('a:not(.action-'+ aClass +')', $options).hide();
						}
					});
				}

				that.deselect();
			});

			$el.on('mouseleave', '.mediumInsert', function () {
				$('a.mediumInsert-buttonsShow', this).removeClass('active');
				$('.mediumInsert-buttonsOptions', this).hide();
			});

			$el.on('click', '.mediumInsert-buttons .mediumInsert-action', function (e) {
				e.preventDefault();

				var addon = $(this).data('addon'),
						action = $(this).data('action'),
						$placeholder = $(this).parents('.mediumInsert-buttons').siblings('.mediumInsert-placeholder');

				if (addons[addon] && addons[addon][action]) {
					addons[addon][action]($placeholder);
				}

				$(this).parents('.mediumInsert').mouseleave();
			});
		}
745946
static private String getPostBackUrlFromHTML(String html)
  {
    Document doc = Jsoup.parse(html);
    Elements e1 = doc.getElementsByTag("body");
    Elements e2 = e1.get(0).getElementsByTag("form");
    String postBackUrl = e2.first().attr("action");
    return postBackUrl;
  }
80384
function(options, select) {
                if (options.length === 0) {
                    return this.nonSelectedText;
                }
                else {
                    var selected = '';
                    options.each(function () {
                        selected += $(this).text() + ', ';
                    });
                    return selected.substr(0, selected.length - 2);
                }
            }
456097
function (html) {
        var self = this;
        var matchedList = html.match(new RegExp(self.DEFINE_LEFT + '.+' + self.RIGHT, 'g'));
        matchedList = _.map(matchedList, function (matched) {
            return matched.substring(self.DEFINE_LEFT.length, matched.length - self.RIGHT.length);
        });
        return matchedList;
    }
351946
function GetHTML(result) {
  if (data.css) result.css = CHTMLSTYLES;
  if (!data.html && !data.htmlNode) return;
  var jax = MathJax.Hub.getAllJax()[0]; if (!jax) return;
  var script = jax.SourceElement(), html = script.previousSibling;

  // add speech text if there isn't one
  if (data.speakText){
    var labelTarget = html.querySelector('.mjx-math');
    for (child of labelTarget.childNodes) child.setAttribute("aria-hidden",true);
    if (!labelTarget.getAttribute("aria-label")){
    labelTarget.setAttribute("aria-label",result.speakText);
    }
  }
  // remove automatically generated IDs
  var ids = html.querySelectorAll('[id^="MJXc-Node-"]');
  for (var i = 0; i < ids.length; i++){
    ids[i].removeAttribute("id");
  }
  // remove extreneous frame element
  var frame = html.querySelector('[id^="MathJax-Element-"]');
  if (frame){
    // in display-mode, the frame is inside the display-style wrapper
    html.insertBefore(frame.firstChild, frame);
    html.removeChild(frame);
  }
  else{
    // otherwise (inline-mode) the frame is the root element
    html.removeAttribute("id");
  }
  if (data.html) result.html = html.outerHTML;
  if (data.htmlNode) result.htmlNode = html;
}
1305594
function getHelpHTML() {
  if (HelpHTML) return HelpHTML

  var helpFile = path.join(__dirname, utils.COMMAND + ".help.txt" )
  var content  = fs.readFileSync(helpFile, "utf8")

  var homepage = "<a href='" + utils.HOMEPAGE + "'>" + utils.HOMEPAGE + "</a>"

  content = content.replace(/%COMMAND%/g,     utils.COMMAND    )
  content = content.replace(/%PACKAGE%/g,     utils.PACKAGE    )
  content = content.replace(/%VERSION%/g,     utils.VERSION    )
  content = content.replace(/%DESCRIPTION%/g, utils.DESCRIPTION)
  content = content.replace(/%HOMEPAGE%/g,    homepage   )

  HelpHTML = "<pre>" + content + "</pre>"
  return HelpHTML
}
666359
function processHTML() {
            /**
             * Genetrate an iterator of the index where non whitespace appear
             * @param {string} text The text to set
             * @returns {number} The index
             */
            function* genWordStartIndices(text) {
                if (!text.trim()) {
                    return
                }
                const re = /\s/u
                let preIsWhitespace = true
                let i = 0
                for (const c of text) {
                    const isWhitespace = re.test(c)
                    if (preIsWhitespace && !isWhitespace) {
                        yield i
                    }
                    preIsWhitespace = isWhitespace
                    i++
                }
            }

            /**
             * Check whether the given token is a dummy element.
             * @param {Token} node The token to check.
             * @returns {boolean} `true` if the token is a dummy element.
             */
            function isDummyElement(node) {
                return (
                    !node.startTag &&
                    (node.name === "body" ||
                        node.name === "head" ||
                        node.name === "html")
                )
            }

            /**
             * Get the start token of Element
             * @param  {Node} elementNode The element node
             * @returns {Token} The start token
             */
            function getStartToken(elementNode) {
                if (!elementNode) {
                    return null
                }
                if (elementNode.type !== "HTMLElement") {
                    return null
                }
                if (isDummyElement(elementNode)) {
                    return null
                }
                return elementNode.startTag || elementNode
            }

            microTemplateService.traverseDocumentNodes({
                HTMLElement(node) {
                    if (isDummyElement(node)) {
                        return
                    }
                    const elementNode =
                        microTemplateService.getBranchProcessedHtmlNode(
                            node,
                            sourceCode
                        ) || node
                    const startToken = getStartToken(elementNode)
                    const parentStartToken = getStartToken(elementNode.parent)
                    if (parentStartToken) {
                        // self indent
                        setOffsetToToken(
                            startToken,
                            1,
                            parentStartToken.loc.start.line
                        )
                    } else {
                        setOffsetRootToIndex(startToken.range[0])
                    }
                    if (
                        IGNORE_INDENT_ELEMENT_NAMES.find(
                            name => name === elementNode.name
                        )
                    ) {
                        ignoreRanges.push([
                            elementNode.startTag
                                ? elementNode.startTag.range[1]
                                : elementNode.range[0],
                            elementNode.endTag
                                ? elementNode.endTag.range[0]
                                : elementNode.range[1],
                        ])
                    }
                },
                HTMLStartTag(node) {
                    const attrs = node.attributes.concat(node.ignoredAttributes)
                    setOffsetToToken(
                        attrs,
                        options.attribute,
                        node.loc.start.line
                    )
                    const start = node.tagOpen
                        ? node.tagOpen.range[1]
                        : node.range[0]
                    const end = node.tagClose
                        ? node.tagClose.range[0]
                        : node.range[1]
                    const attrTemplateTokens = microTemplateService
                        .getMicroTemplateTokens()
                        .filter(token => {
                            if (
                                token.range[0] < start ||
                                end < token.range[1]
                            ) {
                                return false
                            }
                            return !attrs.some(
                                n =>
                                    token.range[0] < n.range[1] &&
                                    n.range[0] < token.range[1]
                            )
                        })
                    setOffsetToToken(
                        attrTemplateTokens,
                        options.attribute,
                        node.loc.start.line
                    )

                    if (node.tagClose) {
                        setOffsetToToken(
                            node.tagClose,
                            options.closeBracket,
                            node.loc.start.line
                        )
                    }
                },
                HTMLEndTag(node) {
                    const endTag =
                        microTemplateService.getBranchProcessedHtmlNode(
                            node,
                            sourceCode
                        ) || node
                    const startToken = getStartToken(endTag.parent)
                    if (startToken) {
                        // self indent
                        setOffsetToToken(endTag, 0, startToken.loc.start.line)
                    }

                    if (endTag.tagClose) {
                        setOffsetToToken(
                            endTag.tagClose,
                            options.closeBracket,
                            endTag.loc.start.line
                        )
                    }
                },
                HTMLText(node) {
                    const textNode =
                        microTemplateService.getBranchProcessedHtmlNode(
                            node,
                            sourceCode
                        ) || node

                    const textHTML = sourceCode.text.slice(
                        textNode.range[0],
                        textNode.range[1]
                    )
                    const startToken = getStartToken(textNode.parent)
                    if (startToken) {
                        // self indent
                        for (const i of genWordStartIndices(textHTML)) {
                            setOffsetToIndex(
                                textNode.range[0] + i,
                                1,
                                startToken.loc.start.line
                            )
                        }
                    } else {
                        for (const i of genWordStartIndices(textHTML)) {
                            setOffsetRootToIndex(textNode.range[0] + i)
                        }
                    }
                },
                HTMLComment(node) {
                    const commentNode =
                        microTemplateService.getBranchProcessedHtmlNode(
                            node,
                            sourceCode
                        ) || node
                    const startToken = getStartToken(commentNode.parent)
                    if (startToken) {
                        // self indent
                        setOffsetToToken(
                            commentNode,
                            1,
                            startToken.loc.start.line
                        )
                    } else {
                        setOffsetRootToIndex(commentNode.range[0])
                    }

                    const commentStart = commentNode.range[0] + 4
                    const commentEnd = commentNode.range[1] - 3
                    const comment = sourceCode.text.slice(
                        commentStart,
                        commentEnd
                    )

                    for (const i of genWordStartIndices(comment)) {
                        setOffsetToIndex(
                            commentStart + i,
                            1,
                            commentNode.loc.start.line
                        )
                    }
                    setOffsetToIndex(commentEnd, 0, commentNode.loc.start.line)
                },
            })
        }