TinyMCE 去掉复制粘贴来的字符串中的标签

  1. 首先去到tinymce.init函数中加入如下代码:
plugins:"paste",
paste_preprocess: function(plugin, args) {
    args.content = strip_tags(args.content,'');
}

第一行是为了让TinyMCE使用paste插件,paste插件中有一个功能是paste_preprocess,他的作用是在字符创粘贴到TinyMCE上前执行一个功能。这里调用了strip_tags函数来去除字符创中的标签,当然也可以去除其他标签。
2. 在当前js文件中添加如下代码:

function strip_tags (str, allowed_tags)
{
    var key = '', allowed = false;
    var matches = [];    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = ''; 
    var replacer = function (search, replace, str) {
        return str.split(search).join(replace);
    };
    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
    }
    str += '';
    // Match tags
    matches = str.match(/(<\/?[\S][^>]*>)/gi);
    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }
        // Save HTML tag
        html = matches[key].toString();
        // Is tag not in allowed list? Remove from str!
        allowed = false;
        // Go through all allowed tags
        for (k in allowed_array) {            // Init
            allowed_tag = allowed_array[k];
            i = -1;
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('+allowed_tag)   ;}

            // Determine
            if (i == 0) {               
                allowed = true;
                break;
            }
        }
        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }
    return str;
}

该段代码,是这个网址一个大牛写的去除字符串中指定的标签项的js代码,用法参照1中所述。

你可能感兴趣的:(ruby,on,rails,JavaScript)