最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove style attributes from string - Stack Overflow

programmeradmin4浏览0评论

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
 |  Show 3 more ments

2 Answers 2

Reset to default 5

If 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>

发布评论

评论列表(0)

  1. 暂无评论