如何从 POST 数据响应中检索子字符串? JS

how to retrieve substring from POST data response? JS

我有一个 POST 请求,它根据发送的表单返回不同百分比的 <p> 标签。示例:

htmlcode = "<p>20%</p >"

每次发送 POST 请求时,我如何获取子字符串、百分比,因为它会发生变化?

首先,如果您不需要数据,为什么将其包裹在 <p>...</p> 标记中?

但是要回答你的问题:

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]);

RegExp 允许您稍后过滤掉一些其他内容,而 substring 版本非常静态。


我注意到您问题中的示例从 <p>20%</p> 更改为 <p>20%</p >。现在我的第一种方法行不通,但是第二种方法会在修改 RegExp 以考虑可选的空格时起作用:

const htmlcode = "<p>20%</p >";

// Using RegExp
const match = htmlcode.match(/^<p>(.*)<\/p\s*>$/);
console.log('match', match[1]);