想問的是有關於match用法
範例1(這個我沒問題)
const input = "As I was going to Saint Ives";
const reg = /\w{3,}/ig;
input.match(reg); //["was","going","Saint","Ives"]
範例2(這裡不大懂)
const html = `<a class="foo" href="/foo" id="foo">Foo</a>\n` +
`<A href ='/foo' Class="foo">Foo</a>\n` +
`<a href="/foo">Foo</a>\n` +
`<a onclick="javascript:alert('foo!')" href="/foo">Foo</a>`;
function sanitizeATag(aTag){
const parts = aTag.match(/<a\s+(.*?)>(.*?)<\/a>/i);
console.log(parts);
}
sanitizeATag(html);
/*
結果:
[
'<a class="foo" href="/foo" id="foo">Foo</a>',
'class="foo" href="/foo" id="foo"',
'Foo',
index: 0,
input: '<a class="foo" href="/foo" id="foo">Foo</a>\n' +
`<A href ='/foo' Class="foo">Foo</a>\n` +
'<a href="/foo">Foo</a>\n' +
`<a onclick="javascript:alert('foo!')" href="/foo">Foo</a>`,
groups: undefined
]
*/
不大懂為什麼範例2,JS怎麼去解讀它?
懇請各位先進不吝指教,我想過1天了,還是看不大懂..
/<a\s+(.*?)>(.*?)<\/a>/i
每個括號都是一個 capturing group
所以match回傳第一個是整個pattren match
然後是<a\s
與>
中間的(.*?)
最後就是 >
與<
中間的(.*?)