【问题标题】:javascript regex to split <p>x</p>javascript 正则表达式拆分 <p>x</p>
【发布时间】:2016-05-30 11:15:33
【问题描述】:

我想按每个 p 标签分割一个 HTML 字符串,所以我得到以下数组:

array{
 '<p>my text</p>',
 '<p>my text2</p>',
 ...
}

这是我尝试过的:

array = articleContent.split(/<p>|(?=<\/p>)/g);

但结果是:

array{
 '</p><p>my text',
 '</p><p>my text2',
 ...
}

【问题讨论】:

标签: javascript regex


【解决方案1】:

你可以这样做!

const re = /\<p>.*?<\/p>/g; //check anything that start/end with tag
const article = "<p>lorem</p> asteroids <p>Ipsum</p>";
const matches = article.match(re); //get the matches
var r = Array.from(matches); //create an array from matches!
console.log(r); // CHECK OUT!

【讨论】:

  • 如果您需要针对多行测试const re = /\&lt;p&gt;.*?&lt;\/p&gt;/gm;
【解决方案2】:

尝试使用以下正则表达式。如果您可以使用示例数据更新您的问题,那就太好了。

/(&lt;p&gt;[A-Za-z\s0-9]+&lt;\/p&gt;)/g

检查输出here

【讨论】:

    【解决方案3】:

    这个:

    /<p>(.*)<\/p>/g.exec('<p>my text</p>')[1];
    

    返回:

    "my text"
    

    【讨论】:

    • 你能解释一下吗?出现在审核队列中。
    • @Will 完整解决方案:data = [ '

      my text

      ', '

      my text2

      '];结果数组 = []; data.forEach(function(element) { resultArray.push( /

      (.*)/g.exec(element)[1] ); });

    【解决方案4】:

    你可以去

    /<p\b.*?<\/p\b[^>]*>/g
    

    它将匹配初始标记和结束标记之前的所有内容(包括属性)。当然……如果你有嵌套标签,那你就完蛋了。

    像这样获取每场比赛:

    var str='<p style="border:1px solid #000">First paragraph with a border</p> is my <p style="color:red">Next paragraph in red</span></p>',
    	re = /<p\b.*?<\/p\b[^>]*>/g,
        m,
        resultingArray = [];
    
    while (m = re.exec(str) )
    {
        resultingArray.push(m[0]);
    }
    
    document.write(resultingArray.join('--------------------') + '<br/>');

    【讨论】:

      猜你喜欢
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 1970-01-01
      • 2018-02-08
      • 2019-07-20
      相关资源
      最近更新 更多