How to extract two strings from url using regex?

I have matched the string successfully, but I need to split it and add some new segments to the url. If this is possible with a regex, how to match the url and extract the two strings like in the example below?

Current result:

["domain.com/collection/430000000000000"]

      

Desired output:

["domain.com/collection/", "430000000000000"]

      

Current code:

var reg = new RegExp('domain.com\/collection\/[0-9]+');
var str = 'http://localhost:3000/#/domain.com/collection/430000000000000?page=0&layout=grid';

console.log(str.match(reg));
      

Run codeHide result


+3


source to share


2 answers


You want Regex Capture Groups .

Place the parts you want to extract in curly braces like this, each part forms a corresponding group:

new RegExp('(domain.com\/collection\/)([0-9]+)') 

      

Then, after matching, you can retrieve the contents of each group by index, with index 0 being an integer match of strings, 1 being the first, second, etc. (thanks for the addition, jcubic!).



This is done using exec()

an inline regex as described here :

/\d(\d)\d/.exec("123");
// โ†’ ["123", "2"]

      

The whole match comes first, then the group matches in the sequence they display in the template.

+3


source


You can declare an array and then fill it with the required values, which you can copy with parentheses (thus using capturing groups )



var reg = /(domain.com\/collection)\/([0-9]+)/g;
//         ^                      ^  ^      ^ 
var str = 'http://localhost:3000/#/domain.com/collection/430000000000000?page=0&layout=grid';
var arr = [];
while ((m = reg.exec(str)) !== null) {
       arr.push(m[1]);
       arr.push(m[2]);
}
console.log(arr);
      

Run codeHide result


Output: ["domain.com/collection", "430000000000000"]

+1


source







All Articles