在字符串中搜索文本并在找到后返回这段文本 - match()

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <p>单击按钮,在字符串化中执行对字母“ain”(/ain)的全局(/g)搜索,并显示匹配项。</p>
  6.  
  7. <button onclick="myFunction()">试一试</button>
  8.  
  9. <p id="demo"></p>
  10.  
  11. <script>
  12. function myFunction() {
  13. var str = "The rain in SPAIN stays mainly in the plain";
  14. var res = str.match(/ain/g);
  15. document.getElementById("demo").innerHTML = res;
  16. }
  17. </script>
  18.  
  19. </body>
  20. </html>