1

I have a string:

var str = `<ul class="errorlist"><li>Enter a valid email address.</li></ul>`;

From this string, how can I extract the substring:

'Enter a valid email address.'

into another variable?

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
HemalHerath
  • 1,006
  • 2
  • 18
  • 38

1 Answers1

7

If the text is not trustworthy, the safest (and probably most elegant) option is to use DOMParser to turn the text into a document, and then select the li in the document:

const str = `<ul class="errorlist"><li>Enter a valid email address.</li></ul>`;
const doc = new DOMParser().parseFromString(str, 'text/html');
const a = doc.querySelector('li').textContent;
console.log(a);

You might be tempted to use the innerHTML of a newly created element:

const str = `<ul class="errorlist"><li>Enter a valid email address.</li></ul>`;
const container = document.createElement('div');
container.innerHTML = str;
const a = container.querySelector('li').textContent;
console.log(a);

But this is unsafe, because error inline handlers may be executed:

const str = `<ul class="errorlist"><li><img src="" onerror="alert('evil')">Enter a valid email address.</li></ul>`;
const container = document.createElement('div');
container.innerHTML = str;
const a = container.querySelector('li').textContent;
console.log(a);

DOMParser does not have the same vulnerability - you can safely use it even when the input string is untrustworthy.

const str = `<ul class="errorlist"><li><img src="" onerror="alert('evil')">Enter a valid email address.</li></ul>`;
const doc = new DOMParser().parseFromString(str, 'text/html');
const a = doc.querySelector('li').textContent;
console.log(a);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320