简体   繁体   中英

Javascript Get Multiple Substrings Within One String

how to get multiple occurences of words in a string. I've tried multiple functions but with no success. I know I can get back the first true value using some() method as below.

       var keyword_array = ["Trap","Samples","WAV","MIDI","Loops"];
        function validateContentKeywords(content,keyword){
                keyword.some(function(currentValue,index){

                     console.log(currentValue + " ");

                     return content.indexOf(currentValue) >= 0;         
                });          
        }
     // Outputs --> Trap Samples
       if(validateContentKeywords("Beat Loops WAV Trap Samples Dog Cat MIDI",keyword_array)){
                console.log("Matches");     
        }
    // What I Want is --> Trap,Samples,MIDI,Loops

The above function only outputs 2 occurences and I want it to output all of the matching values at the same time such as --> Trap,Samples,MIDI,Loops. Is there a way to get multiple occurences of words in a string at the same time?

UPDATED:: The solution that helped me out is below

           function Matches(value){
                return "Beat Loops WAV Trap Samples Dog Cat MIDI".indexOf(value) !== -1;
           }
           var keyword_array = ["Trap","Samples","WAV","MIDI","Loops"].filter(Matches);
            document.write(keyword_array);

您似乎正在寻找可以返回匹配元素数组的filter Array方法 ,而不是返回是否匹配的布尔值。

 var keyword_array = ["Trap", "Samples", "WAV", "MIDI", "Loops"]; function validateContentKeywords(content, keyword) { var words = content.split(' '); //split the given string for (var i = 0; i < words.length; i++) { if (keyword.indexOf(words[i]) > -1) { //check if actually iterated word from string is in the provided keyword array document.write(words[i] + " "); //if it is, write it to the document }; } } validateContentKeywords("Beat Loops WAV Trap Samples Dog Cat MIDI", keyword_array); 

The easiest way to do it would be this:

keyword_array.filter(keyword => searchString.includes(keyword));

You can learn more about filter here . I highly recommend learning about how to use map , reduce and filter . They are your best friends.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM