javascript无法实现前后查找怎么办

javascript无法实现前后查找怎么办

比如这样
hello<h2><span>world</a ></h2><h3>foo</h3> 如何匹配所有 <h([1-6])><\/h\1> 内的内容?

阅读 2.7k
1 个回答

不知道为什么,预览都是正确的,提交之后就乱了

简单的匹配,包含 <h?> 的:

javascript"hello

<h2><span>world</a ></h2>



<h3>foo</h3>

".match(/<(h[1-6])>.*?<\/\1>/g)

// 输出
// ["

<h2><span>world</a ></h2>

", "

<h3>foo</h3>

"]

复杂点的(只取中间那部分)

javascriptvar regex = /<(h[1-6])>(.*?)<\/\1>/g;
var s = "hello

<h2><span>world</a ></h2>



<h3>foo</h3>

";

do {
    var m = regex.exec(s, regex.lastIndex);
    console.log(m);
} while(m);


// 输出
// ["

<h2><span>world</a ></h2>

", "h2", "<span>world</a >", index: 5, input: "hello

<h2><span>world</a ></h2>



<h3>foo</h3>

"]
// ["

<h3>foo</h3>

", "h3", "foo", index: 30, input: "hello

<h2><span>world</a ></h2>



<h3>foo</h3>

"]
// null
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏