preg_match in JavaScript?

后端 未结 8 1884
逝去的感伤
逝去的感伤 2020-12-08 13:17

Is it possible in JavaScript to do something like preg_match does in PHP ?

I would like to be able to get two numbers from str

相关标签:
8条回答
  • 2020-12-08 13:31
    var myregexp = /\[(\d+)\]\[(\d+)\]/;
    var match = myregexp.exec(text);
    if (match != null) {
        var productId = match[1];
        var shopId = match[2];
    } else {
        // no match
    }
    
    0 讨论(0)
  • 2020-12-08 13:35

    Sample code to get image links within HTML content. Like preg_match_all in PHP

    let HTML = '<div class="imageset"><table><tbody><tr><td width="50%"><img src="htt ps://domain.com/uploads/monthly_2019_11/7/1.png.jpg" class="fr-fic fr-dii"></td><td width="50%"><img src="htt ps://domain.com/uploads/monthly_2019_11/7/9.png.jpg" class="fr-fic fr-dii"></td></tr></tbody></table></div>';
    let re = /<img src="(.*?)"/gi;
    let result = HTML.match(re);
    

    out array

    0: "<img src="htt ps://domain.com/uploads/monthly_2019_11/7/1.png.jpg""
    1: "<img src="htt ps://domain.com/uploads/monthly_2019_11/7/9.png.jpg""
    
    0 讨论(0)
  • 2020-12-08 13:40

    JavaScript has a RegExp object which does what you want. The String object has a match() function that will help you out.

    var matches = text.match(/price\[(\d+)\]\[(\d+)\]/);
    var productId = matches[1];
    var shopId    = matches[2];
    
    0 讨论(0)
  • 2020-12-08 13:41

    Some Googling brought me to this :

    function preg_match (regex, str) {
      return (new RegExp(regex).test(str))
    }
    console.log(preg_match("^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$","test"))
    console.log(preg_match("^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$","what@google.com"))

    See https://locutus.io for more info.

    0 讨论(0)
  • 2020-12-08 13:42
    var thisRegex = new RegExp('\[(\d+)\]\[(\d+)\]');
    
    if(!thisRegex.test(text)){
        alert('fail');
    }
    

    I found test to act more preg_match as it provides a Boolean return. However you do have to declare a RegExp var.

    TIP: RegExp adds it's own / at the start and finish, so don't pass them.

    0 讨论(0)
  • 2020-12-08 13:50

    This should work:

    var matches = text.match(/\[(\d+)\][(\d+)\]/);
    var productId = matches[1];
    var shopId = matches[2];
    
    0 讨论(0)
提交回复
热议问题