EugenSunic
EugenSunic

Reputation: 13693

How to extract specific substring from a string using a one liner

Input: parent/123/child/grand-child

Expected output: child

Attempt 1: (?<=\/parent\/\d*)(.*)(?=\/.*)

Error: A quantifier inside a lookbehind makes it non-fixed width, look behind does not accept * but I don't know the width of the number hence must use it

Attempt 2: (works but 2 liners):

const currentRoute='/parent/123/child/grand-child'
let extract = currentRoute.replace(/\/parent\/\d*/g, '');
extract = extract.substring(1, extract.lastIndexOf('/'));
console.log('Result', extract)  

How do I get the extract with a one liner, preferably using regex

Upvotes: 0

Views: 137

Answers (3)

Ωmega
Ωmega

Reputation: 43663

If the format is fixed, then use .split("/")[2] to get 3rd element

console.log(currentRoute.split("/")[2]);

"child"


To match the parent part of the string use .match(/^parent\/[^\/]+\/([^\/]+)/)[1]

console.log(currentRoute.match(/^parent\/[^\/]+\/([^\/]+)/)[1]);

"child"

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163207

Your current pattern will match 123/child instead of child only as there is a forward slash missing after \d* (note the * means 0 or more times)

It will also over match (See demo) due to the .* if there are more forward slashes present.


Instead, you could make use of a capturing group and use match.

parent\/\d+\/(\w+)\/

Regex demo

The value is in capturing group 1.

let res = "parent/123/child/grand-child".match(/parent\/\d+\/(\w+)\//);
if (res) console.log(res[1])


A pattern with a lookbehind to get the value child could be

(?<=parent\/\d*\/)([^\/]+)(?=\/)

Regex demo

Note that this is not yet widely supported.

let res = "parent/123/child/grand-child".match(/(?<=parent\/\d*\/)([^\/]+)(?=\/)/);
if (res) console.log(res[0])

Upvotes: 1

Andre
Andre

Reputation: 788

How about

currentRoute.match(/\/parent\/(?:.*)\/(.*)\//)[1]

Upvotes: 1

Related Questions