How to extract “parts” of a String according to some RegExp pattern?

前端 未结 2 1420
我寻月下人不归
我寻月下人不归 2021-01-27 07:42

In JavaScript, given a regexp pattern and a string:

var pattern = \'/this/[0-9a-zA-Z]+/that/[0-9a-zA-Z]+\';
var str = \'/this/12/that/34\';

How

2条回答
  •  误落风尘
    2021-01-27 08:23

    Use capture groups:

    var res1 = '/this/12/that/34'.match(/\/this\/([0-9a-zA-Z]+)\/that\/([0-9a-zA-Z]+)/);
    

    You will get an array containing 3 elements:

    1. The whole match;

    2. 12

    3. 34

    And you can use .slice(1) to remove the first element:

    var res1 = '/this/12/that/34'.match(/\/this\/([0-9a-zA-Z]+)\/that\/([0-9a-zA-Z]+)/).slice(1);
    

提交回复
热议问题