Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract two strings from url using regex?

I've matched a string successfully, but I need to split it and add some new segments to URL. If it is possible by regex, How to match url and extract two strings like in the example below?

Current result:

["domain.com/collection/430000000000000"]

Desired result:

["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));
like image 922
notif Avatar asked May 03 '26 19:05

notif


2 Answers

You want Regex Capture Groups.

Put the parts you want to extract into braces like this, each part forming a matching group:

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

Then after matching, you can extract each group content by index, with index 0 being the whole string match, 1 the first group, 2 the second etc. (thanks for the addendum, jcubic!).

This is done with exec() on the regex string like described here:

/\d(\d)\d/.exec("123");
// → ["123", "2"]

First comes the whole match, then the group matches in the sequence they appear in the pattern.

like image 108
hiergiltdiestfu Avatar answered May 05 '26 09:05

hiergiltdiestfu


You can declare an array and then fill it with the required values that you can capture with parentheses (thus, making use of 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);

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

like image 31
Wiktor Stribiżew Avatar answered May 05 '26 08:05

Wiktor Stribiżew