Home > OS >  Matching every occurrence, not only the first in JavaScript [duplicate]
Matching every occurrence, not only the first in JavaScript [duplicate]

Time:10-06

I have a text file with the list of sounds and I want to get each sound name from that file.

Javascript:

    <select id='sounds'></select>
    <script>                
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "sounds.txt",!0);
    xmlhttp.onload = function() {
    for (const match of xmlhttp.response.match(/\;([a-zA-Z0-9\s\.\-] )\;/i)) {
    document.getElementById("sound").innerHTML="<option value" match ">" match "</option";}},xmlhttp.send();
    </script>

Sounds.txt:

; Simple Track 1.wav; Simple Track 2.wav; Simple Track 3.wav; Simple Track.wav; Simple Track 1.wav;; Simple Track 2.wav;; Simple Track 3.wav;; Simple Track.wav;

This only returns "Simple Track 1.wav";

The number of files in the txt will not always be the same, so I can't just change

 \;([a-zA-Z0-9\s\.\-] )\; to \;([a-zA-Z0-9\s\.\-] )\;\;([a-zA-Z0-9\s\.\-] )\;\;([a-zA-Z0-9\s\.\-] )\; 

and so on.

CodePudding user response:

You can do this without using a regex:

const test = "; Simple Track 1.wav; Simple Track 2.wav; Simple Track 3.wav; Simple Track.wav; Simple Track 1.wav;; Simple Track 2.wav;; Simple Track 3.wav;; Simple Track.wav;";

const files = test.split(';')
  .filter(f => f !== "")
  .map(m => m.trim());
  
console.log(files);

  • Related