获取没有标签的ckeditor内容的前300个字符

时间:2014-01-23 12:28:51

标签: javascript jquery ckeditor

我正在使用CKEDITOR,在用户输入说明后,我想取前300个字符并将它们放在摘要文本框中。我使用下面的代码从描述ckeditor框移动后使内容移动。当我提醒价值时,它将包括< p>标签。我无法删除用户打算使用它们的字符串。

CKEDITOR.replace( 'property_description' );
CKEDITOR.instances['property_description'].on('blur', function() {
    var value = CKEDITOR.instances['property_description'].getData();
    alert(value);
});

2 个答案:

答案 0 :(得分:2)

使用普通的javascript:

CKEDITOR.replace('property_description');
CKEDITOR.instances['property_description'].on('blur', function() {
    var html = CKEDITOR.instances['property_description'].getData();
    var tmp = document.createElement('div');

    // Strip HTML
    tmp.innerHTML = html;
    var value = tmp.textContent || tmp.innerText;

    // alert truncated value
    alert(value.substring(0, 300);
});

使用jQuery:

CKEDITOR.replace('property_description');
CKEDITOR.instances['property_description'].on('blur', function() {
    var html = CKEDITOR.instances['property_description'].getData();
    var value = $('<div/>', { html: html }).text();

    // alert truncated value
    alert(value.substring(0, 300);
});

答案 1 :(得分:0)

CKEDITOR.replace( 'property_description' );
CKEDITOR.instances['property_description'].on('blur', function() {
    var value = CKEDITOR.instances['property_description'].getData();
    var chars = (((value.replace(/(<([^>]+)>)/ig, "")).replaceHtmlEntites()).replace(/ /g, '')).substring(0, 300);
        alert(chars)
});


String.prototype.replaceHtmlEntites = function () {
    var s = this;
    var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
    var translate = {"nbsp": "", "\t": "", "amp": "&", "quot": "\"", "lt": "<", "gt": ">"};
    return ( s.replace(translate_re, function (match, entity) {
        return translate[entity];
    }) );
};

尝试使用jQuery