简体   繁体   中英

Regular expression that allow some html tags

I'm using AngularJS text editor, I want to add more HTML tags to accepted by text editor other than default HTML tags allowed by editor.

For ex: text editor will allow

<p>,<ul>,<li>,<b>,<ol> ,</p>,</ul>,</li>,</b> and </ol>

What is regular expresses to validate string ?

Please refer below script. Using below function you will able to strip all the HTML tags except the allowed in the function argument.

<script type="text/javascript">
//Function to strip all the tags except allowed tags
function strip_tags(input, allowed) {
    allowed = (((allowed || '') + '')
    .toLowerCase()
    .match(/<[a-z][a-z0-9]*>/g) || [])
    .join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
    commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
    return input.replace(commentsAndPhpTags, '')
    .replace(tags, function($0, $1) {
        return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
    });
}
var str = strip_tags(
   '<p>There is some <u>text</u> here</p>',
   '<p><ul><li><b><ol>' // Allowed tags
);
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM