Gela Ram Gela Ram - 5 months ago 40
Javascript Question

Find a random string from a string via regex (javascript)

I have the following string:

/presentation/d/1JHjE6pWJRujtMQaXcL92HBD8ZKq35au8moEv_zP2D_-0/edit


I want to extract the following using regex:

1JHjE6pWJRujtMQaXcL92HBD8ZKq35au8moEv_zP2D_-0

So far - when i use this 1(/d\W)(.*)\b/1 I get this:

/d/1JHjE6pWJRujtMQaXcL92HBD8ZKq35au8moEv_zP2D_-0/


But I only want to output the string between
/d/
and
/edit


Any help is appreciated.

Answer Source

TL;DR

Provided you always have the string you want to get between a /d/ and an /edit, you can capture it with this regex: (.*\/d\/)(.*)(\/edit.*); it should be the second group.

Below is an illustration of how you can get it:

var data = "/presentation/d/1JHjE6pWJRujtMQaXcL92HBD8ZKq35au8moEv_zP2D_-0/edit";
my_preferred_string = data.match(/(.*\/d\/)(.*)(\/edit.*)/)[2];
console.log(my_preferred_string);


Explaining the regex, /(.*\/d\/)(.*)(\/edit.*)/g:

Here, we have three groups; the groups are confined within brackets as in: (the group elements), where the group elements represents the desired matches.

The 1st group is captured with (.*\/d\/).

In the expression for that group, .* is used to capture any character with the exception of line terminators. In that same portion, we've made use of the quantifier * for matches between zero and unlimited times, as many times as possible. Then, the \/ as a match for the / character (case sensitive), where the preceding \ is an escape, followed by the letter d (case sensitive, to match specifically d as a character), and ending with \/, just as before the d.

The 2nd group which is the actual portion we are interested in is captured with the (.*), where .* is just as explained above in capturing the preceding expression.

The 3rd group is captured with (\/edit.*), where \/ and .* are equally as explained above (group 1), and the edit as a character match for edit (case sensitive).

Finally, the g is a flag (Global pattern flags). It help us get all matches and does not return after we got the first match of our regex.