0

i have this html string

<span style="font-size:25px;border-radius: 10px;">John Doe</span>

from a response. I tried this code to get the John Doe only

const testt = String(response.body)  
const match = testt.match(/^<span style="font-size:25px;border-radius: 10px;">(.*)<\/span>$/);
console.log('match', match[1]);

i recieve null in my logs.

1
  • 1
    There may be extra whitespace around it. Try test1 = response.body.trim() Commented Jul 21, 2021 at 19:26

1 Answer 1

1

JS already has an HTML parser, why not use it?

const html = `
  <span style="font-size:25px;border-radius: 10px;">John Doe</span>
`;

const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
console.log(doc.querySelector("span").textContent);

// or attach to another element
const root = document.createElement("div");
root.innerHTML = html;
console.log(root.querySelector("span").textContent);

If you're in Node, you can use JSDom or Cheerio to achieve the same thing.

const cheerio = require("cheerio");

const html = `
  <span style="font-size:25px;border-radius: 10px;">John Doe</span>
`;
const $ = cheerio.load(html);
console.log($("span").text());

Regardless, please don't use regex to parse HTML.

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

2 Comments

(in node) there are other <span> tags in the response data. I only showed the string I needed in the response since I used String() wouldn't there be an error if used your code since technically it wont know which span tag I want to receive?
You'll need to provide more information to distinguish one span tag from another. Please edit your post to show a larger snippet of the HTML, or provide a live URL I can inspect. Oftentimes, if all that's in the span is some inline styling, it's the parent tags which usually have a predictable structure or classes/ids to work with. Whatever the distinguishing characteristics, though, an HTML parser has the power to make the distinction much better than any other tool. Also, please clarify browser JS or Node.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.