Regular expression for nested tags (innermost to make it easier)

前端 未结 4 871

I researched this quite a bit, but couldn\'t find a working example how to match nested html tags with attributes. I know it is possible to match balanced/neste

4条回答
  •  独厮守ぢ
    2021-01-23 02:47

    You can do it recursively, using the same regex but executed while needed. Like this:

    function htmlToPlainText(html) {
        let text = html || ''
    
        // as there is html nested inside some html attributes, we need a recursive strategy to clean up the html
        while (text !== (text = text.replace(/<[^<>]*>/g, '')));
    
        return text
      }
    

    This works with cases like:

    Lorem Ipsum

    I found this script here: http://blog.stevenlevithan.com/archives/reverse-recursive-pattern

提交回复
热议问题