javascript - 如何提取html字符串中第一段的内容 react native

标签 javascript react-native

我正在开发一个 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/

相关文章:

react-native - iOS模拟器上需要未知模块 "11"错误

reactjs - React Native - Bottom Sheet 始终显示在安装上

javascript - 使用bind修改Angular Controller 内的 "this"

javascript - 这个 Windows 批处理文件如何运行嵌入式 javascript?

css - 在 React Native 中将按钮设置在位置 "fixed"

react-native - 错误 : Unrecognized font family Material Design icons after installing react-native-elements?

react-native - 当 RN 0.61 中的状态发生变化时,如何从主组件重新渲染子组件?

javascript - 使用 svg 圆的 url 填充模式时图像模糊

javascript - 用户脚本访问动态生成的(Vaadin 框架)内容

javascript - 为什么我总是得到 'false' 值?