1. const str = `
    2. <html>
    3. <body>
    4. <div>第一个div</div>
    5. <p>这是一个p</p>
    6. <span>span</span>
    7. <div>第二个div</div>
    8. <body>
    9. </html>
    10. `;
    11. const regExp = /<div>(.*)<\/div>/g;
    12. {
    13. function selectDiv(regExp, str) {
    14. let matches = [];
    15. while (true) {
    16. const match = regExp.exec(str);
    17. if (match == null) {
    18. break;
    19. }
    20. matches.push(match[1]);
    21. }
    22. return matches;
    23. }
    24. const res = selectDiv(regExp, str);
    25. console.log(res); // [ '第一个div', '第二个div' ] 
    26. }
    27. {
    28. console.log(str.match(regExp)); // [ '<div>第一个div</div>', '<div>第二个div</div>' ] 
    29. }
    30. {
    31. function selectDiv(regExp, str) {
    32. let matches = [];
    33. str.replace(regExp, (all, first) => {
    34. matches.push(first);
    35. });
    36. return matches;
    37. }
    38. const res = selectDiv(regExp, str);
    39. console.log(res); // [ '第一个div', '第二个div' ] 
    40. }
    41. {
    42. function selectDiv(regExp, str) {
    43. let matches = [];
    44. for (let match of str.matchAll(regExp)) {
    45. matches.push(match[1]);
    46. }
    47. return matches;
    48. }
    49. const res = selectDiv(regExp, str);
    50. console.log(res); // [ '第一个div', '第二个div' ]
    51. }