-3

How would you remove everything between all instances of brackets like in var item = '<p>1. Get this <a title= "Static Review"> </a> more text </p>'

I've tried using the solution from How can I remove a character from a string using Javascript? with the global tag, formatted like : item = item.replace(/\/<.*>/, ''), but that just outputs nothing.

Really lost here

  • 1
    Parsing html with regex is always a bad idea, there are better ways to parse them, like for your case `element.innerText` might be a better solution. – Shub May 05 '20 at 15:58
  • Hello, yes it's normal that it outputs an empty string. You just removed everything between the first opening bracket and the last closing bracket. – Lorenz Meyer May 05 '20 at 15:59
  • @LorenzMeyer Would it not remove each different cause individually? – Andrew Rose May 05 '20 at 16:00
  • If the string is indeed and HTML string, here's a general method to remove all text: https://jsfiddle.net/terrymorse/qy7ksap6/ – terrymorse May 05 '20 at 16:45

1 Answers1

-1

Just change your line of code by adding a ?:

item = item.replace(/<.*?>/g, '')

While .* is a greedy match, .*? is ungreedy. Greedy means "match as much as you can". Ungreedy means "match as few as possible". Thus <.*?> will stop at the first closing bracket, and do what you want.

The second change to your code: add the /g modifier. In Javascript, /g means "match all occurences", while without, the regex only matches the first occurrence.

Lorenz Meyer
  • 19,166
  • 22
  • 75
  • 121
  • Why the downvote and the delete vote ? Yes there was a typo, but now it's corrected, and this answer does what the OP asked for, and gives additional explanations. – Lorenz Meyer May 05 '20 at 16:08
  • Awesome! That works, one note though there is an extra backslash ```item = item.replace(/\/<.*?>/g, '')``` should be ```item = item.replace(/\<.*?>/g, '')``` – Andrew Rose May 05 '20 at 16:08
  • I didn't do the downvote. – Andrew Rose May 05 '20 at 16:09