![](/img/trans.png)
[英]Strip all attributes from allowed HTML tags when using strip_tags on HTML string using JavaScript
[英]strip characters from string ignoring html tags
我在我的一個項目中將tinyMCE
所見即所得編輯器用於textareas。 我一直在尋找一種方法來限制用戶輸入的字符。
我的要求是:
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;
}
}
一旦綁定到keyDown
或keyUp
事件,此方法就可以正常工作,並且一旦達到字符數限制,就不允許用戶再輸入任何字符。 問題是它不支持copy / paste
因此用戶可以粘貼任意數量的字符。
注意copy
/ paste
。
為了實現copy /paste
功能,我認為最好使用tinyMCE
的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
而不是innerText
剝離字符,並避免剝離字符串中包含的任何HTML標記?
舉例來說,我有以下字符串:
"<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
)執行This is a test. I have been testing this since mor
得到的結果是This is a test. I have been testing this since mor
This is a test. I have been testing this since mor
。 如何獲得包含html標簽的上述結果?
您可以使用此功能:
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>"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.