I have a POST request that comes back as different percentages wrapped in a <p>
tag based on the form sent. example:
htmlcode = "<p>20%</p >"
how would I get the substring, the percentage, as it changes every time a POST request is sent?
I have a POST request that comes back as different percentages wrapped in a <p>
tag based on the form sent. example:
htmlcode = "<p>20%</p >"
how would I get the substring, the percentage, as it changes every time a POST request is sent?
First of all, why is your data wrapped in a <p>...</p>
tag if you don't need it?
But to answer your question:
const htmlcode = "<p>20%</p>";
// Simply substringing
console.log('substring', htmlcode.substring(3, htmlcode.length - 4));
// Using RegExp
const match = htmlcode.match(/^<p>(.*)<\/p>$/);
console.log('match', match[1]);
The RegExp allows you to later on filter out some other things, while the substring
version is very static.
I noticed that the example in your question changed from <p>20%</p>
to <p>20%</p >
. Now my first approach won't work, but the 2nd one will when modifying the RegExp to account for optional whitespace:
const htmlcode = "<p>20%</p >";
// Using RegExp
const match = htmlcode.match(/^<p>(.*)<\/p\s*>$/);
console.log('match', match[1]);
...
`, so check what your HTML request returns. – Kelvin Schoofs Jul 21 '21 at 17:32
` and `
` are always wrapping the percentage, you can replace them to nothing. It will leave you with only - say - '20%'. At that point, you just replace the "%" sign with nothing, and you get the number. – GrafiCode Jul 21 '21 at 17:07', '').replace('
', '').replace('%'. '');` – GrafiCode Jul 21 '21 at 17:09