1
let titles = this.state.posts.slice(0, 3).map(function(title, index) {
  let regex = /<style(.+?)\/style>/gm;
  let res = regex.exec(title.content.rendered);
  console.log(res);
  return (
    <div key={index}>
      <p className="title has-text-black">{title.title.rendered}</p>
      <div className=" has-text-black">{title.content.rendered.replace(regex, '')}</div>
    </div>
  );
});

I try to fetch some posts from wordpress rest api, the content.rendered return a string include html, style tags etc. And i want it just a pure text with no html tags. I wonder why the regex above won't work? I did try other regex, it works, but not this anything-in-style-tags-remover regex.

fauxxi
  • 75
  • 10
  • 1
    You capture what is inside the tags into Group 1, did you use `res[1]`? I see you just return the input, `{title.title.rendered}` – Wiktor Stribiżew Sep 25 '18 at 16:08
  • yes, but for now forget everything in return(), it's only temporary, first i wanna test first the regex itself, but here in consol.log(res) it returns null, because the regex is invalid. @WiktorStribiżew – fauxxi Sep 25 '18 at 16:17
  • 1
    @fauxxi, please provide the HTML that the regex is running over. – ryanpcmcquen Sep 25 '18 at 16:18
  • 2
    Does it mean you have line breaks in your text between `style` and `/style`? – Wiktor Stribiżew Sep 25 '18 at 16:18
  • `exec ` is mutable operation and can result null after second invocation, check if you called it multiple times. – Rafael Hovsepyan Sep 25 '18 at 16:29
  • 2
    Beware that your RegExp is going to match everything between multiple style tags also. You might want to read this: https://stackoverflow.com/a/1732454/434742 on why RegExp and HTML is a no good combination. You should parse the HTML with a proper library and work with that result. – Krisztián Balla Sep 25 '18 at 16:55
  • @WiktorStribiżew oh yess it works! thanks, finally i also add `/(<([^>]+)>)/g` to completely remove all html tags, and get a clean text! ^^ – fauxxi Sep 25 '18 at 17:34
  • @JennyO'Reilly well, in this case, all those html class are in a string from an object json, so i assume that is not a 'pure' HTML – fauxxi Sep 25 '18 at 17:36

0 Answers0