从Javascript中的文本中删除标记,并用textarea中的换行符替换BR

时间:2011-03-30 04:06:57

标签: javascript jquery regex

我需要在输入textarea值中导入一些格式化的html文本

我使用jquery

那么最好的方法是什么? 我想首先我需要更换然后剥去其余的(粗体,斜体,图像等..)

2 个答案:

答案 0 :(得分:2)

在我的第一个回复中,我没有看到你想保留换行符,所以这里是一个更好的版本。它用不可能的字符串%% br %%替换br,然后在最后用新行替换它们(\ n)。因此,如果该字符串实际出现在文本中,它将被替换为新行。您可以将其更改为您喜欢的任何内容,只需将其设置为文本中不太可能遇到的内容。

<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>

答案 1 :(得分:0)

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

示例:http://jsfiddle.net/6WbXN/