2

how to remove all tags in a string but not <a>? and not the text inside them?

For example: <em>Bold</em><a>Go here</a> should be: Bold<a>Go here</a>

2
  • 2
    Do you want to manipulate a string, or the DOM? Why do you tag regex? Depending on the first question, you may not need them. Commented Sep 4, 2015 at 14:37
  • You shouldn't ... Commented Sep 4, 2015 at 14:54

2 Answers 2

2

You can remove all strings that look like <...> other than <a> or </a> with

<(?!\/?a>)[^>]*>

See demo

Do not forget to add a /i case insensitive modifier to also avoid matching <A>. If you do not plan to keep closing </a>, you can use <(?!a>)[^>]*>.

Sign up to request clarification or add additional context in comments.

1 Comment

I added optional \/? - I guess you wanted to also keep the closing tag, right? I also added the note with my previous regex.
1

Try this:

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 html = 'some html code';
html = strip_tags(html, '<a>');

source: http://phpjs.org/functions/strip_tags/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.