简体   繁体   中英

What is the Javascript Regexp for finding the attributes in a <span> tags?

I have a <div contenteditable="true> that I am trying to use to get text from users. I would use a simple <textarea> , but I need line-breaks and eventually lists and tables etc. I am trying to build something that is semi a rich-text editor, but not a full fledged one. I do not want to use a rich text editor.

I am trying to eliminate the attributes on <span> tags from the text that is typed into the <div contenteditable="true> . Is there a way to do that with Regexp? I was having difficulties coming up with a Regexp because I can't figure out how to make it so that the string starts with <span and ends with > and any number of characters can be in between. Is there a way to combine that in one Regexp? I came up with /^<span >$/ but that does not work because there is no division between the two strings. Would something like this work: /^[<span][>]$/g ?

Parse the HTML and then strip out the attributes afterwards. If you're doing this in a browser, you have a high grade HTML parser right at your disposal (or you have IE) , so use it!

Use DOM functions for it. Here's some code using jQuery to make it easier and nicer to read:

$('#your-div span').each(function() {
    var elem = this, $elem = $(this);
    $.each(elem.attributes, function(i, attr) {
        if(attr) {
            $elem.removeAttr(attr.name);
        }
    });
});

Demo: http://jsfiddle.net/ThiefMaster/qfsAb/

However, in your case you might want to remove attributes not only from spans but from all elements unless the attribute is eg align or href .

So, here's some JS for that: http://jsfiddle.net/ThiefMaster/qfsAb/1/

$('#your-div').children().each(function() {
    var elem = this, $elem = $(this);
    $.each(elem.attributes, function(i, attr) {
        if(attr && attr.name != 'href' && attr.name != 'align') {
            $elem.removeAttr(attr.name);
        }
    });
});

I made a working demo at http://jsfiddle.net/b3DSQ/

$('#editor span').each(function(i, el) {
    var attrs = el.attributes;
    $.each(attrs, function(i, a) {
        $(el).removeAttr(a.name);
    });
});

[I changed an earlier version which copied the contents into memory, edited, and then replaced - hadn't realised that the stuff typed into the div was automatically valid in the DOM].

Try this:

your_string.replace(/<span[^>]*>/g, '<span>');

This will break however if the user writes something like <span title="Go > there">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM