RegEx to extract all matches from string using RegExp.exec

前端 未结 17 1500
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:49

I\'m trying to parse the following kind of string:

[key:\"val\" key2:\"val2\"]

where there are arbitrary key:\"val\" pairs inside. I want t

17条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 03:18

    I would definatly recommend using the String.match() function, and creating a relevant RegEx for it. My example is with a list of strings, which is often necessary when scanning user inputs for keywords and phrases.

        // 1) Define keywords
        var keywords = ['apple', 'orange', 'banana'];
    
        // 2) Create regex, pass "i" for case-insensitive and "g" for global search
        regex = new RegExp("(" + keywords.join('|') + ")", "ig");
        => /(apple|orange|banana)/gi
    
        // 3) Match it against any string to get all matches 
        "Test string for ORANGE's or apples were mentioned".match(regex);
        => ["ORANGE", "apple"]
    

    Hope this helps!

提交回复
热议问题