3

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));

5
  • if domain.com/collection/ is always a known constant then why not just do "domain.com/collection/430000000000000".split('domain.com/collection/') Commented May 27, 2015 at 12:17
  • @vsync there are stuff after id. Commented May 27, 2015 at 12:18
  • @jcubic - so? split it again. show me a scenario where this might fail if you may Commented May 27, 2015 at 12:32
  • @vsync you will have ['http://localhost:3000/#', '430000000000000?page=0&layout=grid']. or ["http://localhost:3000/#/", "domain.com/collection/", "430000000000000?page=0&layout=grid"] if you keep the split text. Commented May 27, 2015 at 13:36
  • @jcubic - no I won't.. anyway the hash is after that number and never before, so you split for a hash again or whatever might be after.. it will work Commented May 27, 2015 at 14:05

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

0 index is always match for whole regex.
1

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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.