jQuery (almost) equivalent of PHP's strip_tags()

后端 未结 9 794
忘掉有多难
忘掉有多难 2020-11-27 04:50

Is there a jQuery version of this function?

string strip_tags( string $str [, string $allowable_tags ] )

stri

相关标签:
9条回答
  • 2020-11-27 05:24

    You can try this, probably best solution: http://phpjs.org/functions/strip_tags/

    0 讨论(0)
  • 2020-11-27 05:29

    This worked for me:

    function strip_tags(str) {
        str = str.toString();
        return str.replace(/<\/?[^>]+>/gi, '');
    }
    
    0 讨论(0)
  • 2020-11-27 05:31

    Even if this is an old thread i think it could be useful for those who are still looking for an answer.

    The Locutus.io function seems to be the best solution:

    function strip_tags (input, allowed) {
          allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('')
          var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi
          var commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi
          return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
            return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ''
          })
    }
    

    Example 1:

    strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>')
    

    returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'

    Example 2:

    strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>')
    

    returns 2: '<p>Kevin van Zonneveld</p>'

    Example 3:

    strip_tags("<a href='http://kvz.io'>Kevin van Zonneveld</a>", "<a>")
    

    returns 3: "<a href='http://kvz.io'>Kevin van Zonneveld</a>"

    Example 4:

    strip_tags('1 < 5 5 > 1')
    

    returns 4: '1 < 5 5 > 1'

    Example 5:

    strip_tags('1 <br/> 1')
    

    returns 5: '1 1'

    Example 6:

    strip_tags('1 <br/> 1', '<br>')
    

    returns 6: '1 <br/> 1'

    Example 7:

    strip_tags('1 <br/> 1', '<br><br/>')
    

    returns 7: '1 <br/> 1'

    0 讨论(0)
提交回复
热议问题