JavaScript如何提取字符串中的指定首段目标内容
解法1:直接用正则匹配整段字符串(最稳定)
不需要提前做split操作,直接从原始字符串中提取<strong>标签包裹的内容即可:
const str = "example.com/en/en/some-text/test%C5%84sk/<strong>thispartofcharIwant</strong>-thisnot-not/not"; // 匹配<strong>和</strong>之间的内容,取捕获组结果 const target = str.match(/<strong>([^<]+)<\/strong>/)?.[1]; console.log(target); // 输出 thispartofcharIwant
解法2:基于你现有代码补充处理
你已经通过split('/')[5]拿到了包含目标内容的片段,只需要对该片段做二次处理即可:
const myArr = str.split("/")[5]; // 先切掉</strong>及之后的所有内容,再移除开头的<strong>标签 const target = myArr.split('</strong>')[0].replace('<strong>',''); console.log(target); // 输出 thispartofcharIwant
内容的提问来源于stack exchange,提问作者Marcin Milowski
相关产品推荐
相关产品推荐

