从字符串中删除html标记中的字符

时间:2013-09-16 11:20:58

标签: javascript jquery html regex tinymce

我在我的一个项目中使用tinyMCE所见即所得的编辑器来处理textareas。我一直在寻找一种方法来限制用户输入的字符。

我的要求是:

  • 不要让用户输入超过指定字符数限制。 (因此该方法应绑定到keyDown / keyUp事件)。
  • 确保这也适用于复制/粘贴(即ctrl+v和右侧 鼠标单击并paste)。
  • 在复制/粘贴时,行为应该是 - >从innerText中删除多余的字符,并将内容设置为已剥离的文字,但仍保留应用于原始内容的styles

我已经看过maxchars插件,但它不能达到目的,特别是在涉及copy / paste功能时。我尝试实现自定义方法来实现上述要求。

我已经取得的成就如下:


阻止用户在达到字符数限制后再输入任何字符。

function preventExcessChars(editor, event) {
    var body = editor.getBody(),
        limit = editor.settings.charLimit,
        text = body.innerText || body.textContent,
        length = text.length;

    if (length >= limit && isCharacterKeyPress(event)) {
        event.preventDefault();
        event.stopImmediatePropagation();
        return false;
    }   
}

一旦绑定到keyDownkeyUp事件,此工作正常,并且一旦达到字符限制,就不允许用户输入任何字符。这个问题是它不支持copy / paste,因此用户可以根据需要粘贴任意数量的字符。

照顾copy / paste

为了实现copy /paste功能,我认为最好使用tinyMCE的{​​{1}}方法来更新内容。所以我将上述内容更新为:

setContent

这非常有效。这样做的问题在于它不会将原始内容中的样式应用于新内容,因为新内容为function preventExcessChars(editor, event) { var body = editor.getBody(), limit = editor.settings.charLimit, text = body.innerText || body.textContent, length = text.length; if (length >= limit && isCharacterKeyPress(event)) { // update the content and use setContent to update the text area var new_content = text.substr(0, limit); editor.setContent(new_content); event.preventDefault(); event.stopImmediatePropagation(); return false; } } 对象。


有没有办法可以从innerText而不是innerHTML删除字符,并避免剥离字符串中包含的任何HTML标记?

例如,假设我有以下字符串:

innerText

上述字符串的 "<p>This is a <b>test</b>.</p><p>I have been <i>testing</i> this since morning.</p>"; 长度为innerText个字符,并且限制为55个字符。我想从上面的字符串中去掉最后的50个字符,结果是:

5

如果我使用上面的代码(即使用 "<p>This is a <b>test</b>.</p><p>I have been <i>testing</i> this since mor</p>" )执行此操作,我得到的结果是innerText。如何获得包含html标签的上述结果?

1 个答案:

答案 0 :(得分:0)

您可以使用此功能:

function maxChars(str, max) {
  var tags = 0,
      sQuotes = 0,
      dQuotes = 0,
      char,
      count = 0,
      result = [];
  for (var i = 0, len = str.length; i < len; ++i) {
    char = str.charAt(i);
    switch(char) {
      case '<':
        if (!sQuotes && !dQuotes) {
          ++tags;
          result.push(char);
          continue;
        }
        break;
      case '>':
        if (!sQuotes && !dQuotes) {
          --tags;
          result.push(char);
          continue;
        }
        break;
      case "'":
        if (tags && !dQuotes)
          sQuotes = !sQuotes;
        break;
      case '"':
        if (tags && !sQuotes)
          dQuotes = !dQuotes;
        break;
    }
    if (tags) {
      result.push(char);
    } else {
      if (++count < max)
        result.push(char);
    }
  }
  return result.join('');
};

// Example
var text = "<p>This is a <b>test</b>.</p><p>I have been <i>testing</i> this since morning.</p>";
maxChars(text, 50);
// "<p>This is a <b>test</b>.</p><p>I have been <i>testing</i> this since mor</p>"