preg_match_all JS equivalent?

前端 未结 4 1515
孤独总比滥情好
孤独总比滥情好 2021-02-05 09:47

Is there an equivalent of PHP\'s preg_match_all in Javascript? If not, what would be the best way to get all matches of a regular expression into an array? I\'m willing to use a

相关标签:
4条回答
  • 2021-02-05 09:58

    You can use match with the global modifier:

    >>> '1 2 3 4'.match(/\d/g);
    ["1", "2", "3", "4"]
    
    0 讨论(0)
  • 2021-02-05 09:58

    John Resig has written about a great technique on his blog called 'Search and dont replace'

    It works using javascript's replace function, which takes a callback function, and returns nothing to leave the original content unaltered.

    This can be a neater than using a global match and iterating over an array of results, especially if you're capturing several groups.

    0 讨论(0)
  • 2021-02-05 09:58

    Use new RegExp().test()

    function preg_match_all(regex, str) {
      return new RegExp(regex,'g').test(str)
    }

    0 讨论(0)
  • 2021-02-05 10:18

    A better equivalent of preg_match_all from PHP in JS would be to use the exec() function. This will allow you to capture groups as well, with match() you can not do that.

    For example you want to capture all times and the number in brackets from the variable myString:

    var myString = "10:30 am (15 left)11:00 am (15 left)11:30 am";
    var pattern = /(\d{1,2}:\d{1,2}\s?[ap]m)\s\((\d+)/gi;
    var match;
    while (match = pattern.exec(myString)){
      console.log('Match: "' + match[0] + '" first group: -> "' + match[1] + '" second group -> ' + match[2]);
    }
    

    The output will be:

    Match: "10:30 am (15" first group: -> "10:30 am" second group -> 15
    Match: "11:00 am (15" first group: -> "11:00 am" second group -> 15
    
    0 讨论(0)
提交回复
热议问题