-1

I've seen a lot of posts with regex for specific tags but what if a tag has a class or an ID or any attribute for that matter. How would I get just the text between the span tags. I have some places where the span and h tags doesn't have any class but most have.

const html = <h4><span  class="title">Lorem ipsum..</span></h5><h3><span id="bl">xvcxv</span>

I've tried this from another post but its not what I'm after.

html.match(/<span>([\s\S]*)(?=<\span/>)/g);
2
  • You could try some of the solutions in this post: stackoverflow.com/questions/5002111/… Commented Jan 30, 2019 at 3:17
  • Thanks Doug but the regex in that link is for stripping tags out. I'm only looking to return text between the span tags. Commented Jan 30, 2019 at 3:25

1 Answer 1

2

In your regex your are escaping the s like \s which turns its meaning into matching a whitespace character. Your regex will then match for example <span>test< pan/>

The closing span <\span/> should not contain a forward slash. The content is in the first capturing group, you can match the <\/span> instead of using a positive lookahead.

This part [\s\S]* is greedy meaning it will match until the last occurrence where < pan/> follows.

For your example data you could match not a closing angle bracket <span[^>]*>, but is not advisable to parse html using a regex. Another option could be to use a DOMParser:

const html = `<h4><span  class="title">Lorem ipsum..</span></h5><h3><span id="bl">xvcxv</span>`;
let parser = new DOMParser();
let doc = parser.parseFromString(html, "text/html");
doc.querySelectorAll("span").forEach(s => console.log(s.innerHTML));

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

2 Comments

As a variant, OP can insert his HTML into some var div = document.createElement("div") as div.innerHTML = html, and then just use div.querySelectorAll("span") as you've described :) Of course, if there is any DOM in OP's namespace
@LevitatorImbalance You are right, that is also possible.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.