如何在React中拆分DOM内容并精准提取指定句子?
问题
需要在React中处理DOM内容,精准提取指定句子:“我们的客户是一家备受尊敬的搬家公司,现正在招聘一名全国账户搬家协调员加入他们的远程团队。”(原英文:"Our client, a highly respected moving company is seeking a National Account Move Coordinator to join their team based remotely.")
当前代码会提取全部文本而非目标句子,示例DOM结构如下:
<article> Our client, a highly respected moving company is seeking a National Account Move Coordinator to join their team based remotely. <br> <br> The successful candidate will have experience within the Household Goods Moving and Relocation Industry. <br> <br> <strong>National Account Move Coordinator responsibilities:</strong> </article>
当前使用的代码:
const body = 'We are hiring for the following opportunity: \n' + job.title + ' - ' + job.location + ' \n' + job?.description.replace(/<[^>]*>?/gm, '').replace(' ', ' ').split("<br><br>")[0] + '... \n\n';
解决方案
问题出在代码执行顺序:你先把所有HTML标签(包括<br><br>)都替换掉了,之后再用<br><br>拆分自然找不到匹配项,导致提取了全部内容。正确逻辑是先拆分段落,再清理标签。
修改后的代码
const body = '我们正在招聘以下岗位:\n' + `${job.title} - ${job.location}\n` + `${job?.description.split('<br><br>')[0] .replace(/<[^>]*>?/gm, '') .replace(' ', ' ')}...\n\n`;
逻辑说明
- 先拆分:用
<br><br>作为分隔符拆分DOM内容,取第一个片段(也就是目标句子所在的第一段) - 后清理:对这个片段清除所有HTML标签,再替换
为空格,保证文本格式正常
备选方案(固定目标句子场景)
如果目标句子是固定不变的,也可以直接用正则匹配提取:
// 匹配固定目标句子 const targetMatch = job?.description.match(/Our client, a highly respected moving company is seeking a National Account Move Coordinator to join their team based remotely\./); const targetSentence = targetMatch ? targetMatch[0] : ''; const body = '我们正在招聘以下岗位:\n' + `${job.title} - ${job.location}\n` + `${targetSentence.replace(/<[^>]*>?/gm, '').replace(' ', ' ')}...\n\n`;
内容的提问来源于stack exchange,提问作者Teik Cheah
相关产品推荐
相关产品推荐

