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

后端 未结 9 793
忘掉有多难
忘掉有多难 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:09

    To remove all tags you can use

    $('<div>Content</div>').text()
    
    0 讨论(0)
  • 2020-11-27 05:13

    To remove just the tags, and not the content, which is how PHP's strip_tags() behaves, you can do:

    var whitelist = "p"; // for more tags use the multiple selector, e.g. "p, img"
    $("#text *").not(whitelist).each(function() {
        var content = $(this).contents();
        $(this).replaceWith(content);
    });
    

    Try it out here.

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

    Just use a regular expression:

    html.replace( /<.*?>/g, '' );
    

    Done. :)

    For the p tag:

    html.replace( /<[^p].*?>/g, '' );
    

    For other tags, it gets more complicated.

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

    UPDATE

    Use the following to strip tags while keeping content

    $('#text').find('p').contents().unwrap();
    

    This will strip p tag where p is a child element of '#text'.

    Check working example at http://jsfiddle.net/YWCsH/

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

    Not an actual answer, but a word of caution (depending on what you're trying to do with this):

    IMHO, in almost all cases, input sanitization should be done on the server side (in this case, using the native PHP functions). If your intent is to replace PHP functionality with client-side functionality, I would strongly advise against it.

    Why?

    Just because you're authoring a website, it doesn't mean that:

    1. Your users have JavaScript enabled. If you aren't submitting your form strictly through script (using submit buttons, etc), it still allows users to submit invalid data (such as <script> tags, etc.)
    2. Requests may not actually be initiated by a browser at all, circumventing any JS-based input sanitization.

    Again, not really answering your question, but a word of caution based on where you could possibly be headed based on your question :)

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

    To remove all tags, could use:

    var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");
    

    Code from: Strip HTML Tags in JavaScript

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