Learner
Learner

Reputation: 2339

Can someone let me know the best way to remove particular inline CSS style from a string?

I have a string that has html / CSS in it ( The string is created using rich text editor). The data is used by multiple applications, some applications use the format as is, some try to apply new format to the data. We dont have any issues with html, since its easy to remove those data.

I am not sure what's the best way to remove a particular CSS from the string.FYI...Some string might not contain CSS....I am thinking of using regular expression.. but not quite sure if it is a foolproof way....

I know we can use the below way to remove

document.getElementById("whatever").className = "";
$('whatever').remmoveClass();

but this removes all the CSS styles.

For Ex: I need to remove just the below inline CSS from the text below

<style type="text/css"> p { text-indent: 0pt;padding: 0px 0px 0px 0px;margin-top: 0px;margin-right: 0px;margin-bottom: 12px;margin-left: 0px;text-align: left;font-family: 'Verdana';font-style: Normal;font-weight: normal;font-size: 16px;color: #000000; } .defaultDocumentStyle { telerik-style-type: default;telerik-style-name: defaultDocumentStyle;font-family: 'Verdana';font-style: Normal;font-weight: bold;font-size: 10.6700000762939px;margin-bottom: 12px; } </style><p><span>ddfggfg</span></p>

I need just need ddfggfg

EDIT: The string might not necessarily be a html string since they can use the simple text editor too hence I cant assume the string will contain HTML.

I have this issue mainly when exporting the data to CSV / PDF. The inline CSS class gets exported along with the data.

Thanks,
Barani

Upvotes: 1

Views: 138

Answers (2)

SLaks
SLaks

Reputation: 887415

You need to parse the HTML and remove the style="" and perhaps class="" attributes.

Using jQuery:

var dom = $('<div>' + source + '</div>');
dom.find('*').removeAttr('style');
var cleaned = dom.html();

You may also want to .find('style') and .remove() them.

Upvotes: 4

Nate Kindrew
Nate Kindrew

Reputation: 861

What about setting specific styles to override whatever might get set by the editor? If you have a specific class or ID in which the content is placed, you could do something like the following in your CSS:

#whatever p{
    margin-bottom: 0px !important;
}

That's just a short example, but if you have a specific way you want it to look, you could set up a few overrides to ensure consistent styling. The downside is that you have to override every CSS property that is in conflict with how you expect it to look.

Upvotes: 0

Related Questions