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

后端 未结 9 821
忘掉有多难
忘掉有多难 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: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 = /|<\?(?:php)?[\s\S]*?\?>/gi
          return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
            return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ''
          })
    }
    

    Example 1:

    strip_tags('

    Kevin


    van Zonneveld', '')

    returns 1: 'Kevin van Zonneveld'

    Example 2:

    strip_tags('

    Kevin van Zonneveld

    ', '

    ')

    returns 2: '

    Kevin van Zonneveld

    '

    Example 3:

    strip_tags("Kevin van Zonneveld", "")
    

    returns 3: "Kevin van Zonneveld"

    Example 4:

    strip_tags('1 < 5 5 > 1')
    

    returns 4: '1 < 5 5 > 1'

    Example 5:

    strip_tags('1 
    1')

    returns 5: '1 1'

    Example 6:

    strip_tags('1 
    1', '
    ')

    returns 6: '1
    1'

    Example 7:

    strip_tags('1 
    1', '

    ')

    returns 7: '1
    1'

提交回复
热议问题