I'm trying to remove all style attributes from a string (and not an object), in JavaScript or jQuery.
Example
var html = "<p style="color:red">my text</p>";
And I want to obtain this:
<p>my text</p>
Is it possible to do it without calling the functions that we can call on objects (as removeAttr
)?
Thanks
I'm trying to remove all style attributes from a string (and not an object), in JavaScript or jQuery.
Example
var html = "<p style="color:red">my text</p>";
And I want to obtain this:
<p>my text</p>
Is it possible to do it without calling the functions that we can call on objects (as removeAttr
)?
Thanks
Share Improve this question edited Jan 8, 2021 at 13:09 MaxiGui 6,3584 gold badges18 silver badges35 bronze badges asked May 31, 2017 at 13:31 useruser 5451 gold badge11 silver badges32 bronze badges 8- 2 And why do you want to do this using string manipulation, rather than DOM approaches which avoid the edge-cases of using regular expressions to parse HTML strings? – David Thomas Commented May 31, 2017 at 13:35
- Cause i never get the full html when putting the string in an object – user Commented May 31, 2017 at 13:36
- you can use regexes on simple html strings but heavily nested html is not a good use case for regex. so it depends, will your html strings be single nodes like the example? – James Commented May 31, 2017 at 13:37
- No my html is much more plex. many levels ... – user Commented May 31, 2017 at 13:38
- 1 You must use regexp, no other way, use this site regex101. it helps a lot to understund regular expressions, also this developer.mozilla/pl/docs/Web/JavaScript/Guide/… es in handy – Luke Commented May 31, 2017 at 13:55
2 Answers
Reset to default 5If you are not looking to use JavaScript or jQuery objects, have you tried using regular expressions?
This answer to a previous question shows a php version that can be adapted to JavaScript using the replace
function.
See if this helps.
$("button").click(function() {
$("p").removeAttr("style");
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p style="color:red">my text</p>
<button>Remove the style attribute from all p elements</button>