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
?
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 e.g. 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);
}
});
});
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!
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">
精彩评论