开发者

Strip tags from text in Javascript and replace BR with linebreaks inside textarea

I need to import some formatted html text in a input textarea value

i use jquery

so what's the best way to do it? i guess first of开发者_C百科f i need to replace the

then strip out the rest (bold, italic, images etc..)


In my first response I didn't see that you wanted to retain line breaks, so here's a better version. It replaces br with an unlikely string %%br%% and then at the end replaces them with new line (\n). So if that string actually appears in the text, it will be replaced by a new line. You can change that to anything you like, just make it something that is unlikely to be encountered in the text.

<script>

function removeMarkup(m) {
  var d = document.createElement('div');
  d.innerHTML = m;
  var c = 0;

  // Make brString something that should never appear in the text
  // and has no special meaning in a RegExp
  var brString = '%%br%%'
  var re = new RegExp('\\s*' + brString + '\\s*','g');

  function getTextWithReturns(node) {

    var tag = node.tagName && node.tagName.toLowerCase();
    var nodes = node.childNodes;
    var type = node.nodeType;
    var s = '';

    // Deal with br
    if (tag == 'br') {
      return brString;
    }

    if (nodes && nodes.length) {
      for (var i=0, iLen=nodes.length; i<iLen; i++) {
        s += getTextWithReturns(nodes[i]);
      }
    } else if (type == 3 || type == 4) {
      s += node.nodeValue
    } 
    return s;
  }
  return reduceWhitespace(getTextWithReturns(d)).replace(re,'\n');
}

function reduceWhitespace(s) {
  return s.replace(/^\s*/,'').replace(/\s*$/,'').replace(/\s+/g,' ');
}

</script>

<div id="d0">some text <i>more</i> text
  <p>Here is a paragraph with some <b>bold</b> and <i>italic</i> text, plus a <span>span</span> and a line break break break<br> about there.</p>
  <p>Here is another paragraph with some <b>bold</b> and <i>italic</i> text, plus plus a <span>span</span> and a line break <br> here.</p>
</div>

<form>
<textarea id="ta0" rows="10" cols="50"></textarea>
<button type="button" onclick="
  var ta = document.getElementById('ta0');
  var div = document.getElementById('d0');
  ta.value = removeMarkup(div.innerHTML);
">Set value</button><input type="reset">
</form>


$("#my_textarea").change(function(){
    var cleanText = $("<span />").html(this.value);
    this.value = cleanText.text();
});

Example: http://jsfiddle.net/6WbXN/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜