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 Answers1

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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • (in node) there are other `` 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? – Bobby Byen Jul 21 '21 at 20:11
  • 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. – ggorlen Jul 21 '21 at 20:29