我正在开发一个 React Native 项目,并且我有一个 html 字符串 json api 响应。 我正在使用react-native-render-html来渲染它,我可以获取所有段落并应用特定的东西,例如行数等。但是我只想得到响应中的第一段。
str response='<p>text1</p> <p>text2</p> <p>text3</p>';
是否可以编写正则表达式来仅获取第一段的内容,例如 text1 ?
最佳答案
我不使用 React Native,但在 javascript 中你可以做类似的事情:
const paragraphs = response.split("</p>")
const firstParagraph = paragraphs[0]+'</p>';
或者使用正则表达式,您可以执行类似的操作:
// extract all paragraphe from the string
const matches = [];
response.replace(/<p>(.*?)<\/p>/g, function () {
//use arguments[0] if you need to keep <p></p> html tags
matches.push(arguments[1]);
});
// get first paragraph
const firstParagraph = (matches.length) ? matches[0] : ""
或者像这样(我认为这是针对你的情况最好的方法)
const response='<p>text1</p> <p>text2</p> <p>text3</p>';
const regex = /<p>(.*?)<\/p>/;
const corresp = regex.exec(response);
const firstParagraph = (corresp) ? corresp[0] : "" // <p>text1</p>
const firstParagraphWithoutHtml = (corresp) ? corresp[1] : "" // text1
关于javascript - 如何提取html字符串中第一段的内容 react native ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61791863/