Gela Ram Gela Ram - 1 year ago 78
Javascript Question

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

I have the following string:


I want to extract the following using regex:


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


But I only want to output the string between

Any help is appreciated.

Answer Source


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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download