Search code examples
javascriptpythonregexregular-language

Regular Express for Javascript - Contain a specific word in the beginning after get any character until a certain character comes


I need a certain type of regular expression where I need list of special type of strings from a string. Example input:

str = 'this is extra data which i do not need /type/123456/weqweqweqweqw/ these are more extra data which i dont need /'

Result needed:

/type/123456/weqweqweqweqw/

Here the /type/ string will be constant and the remaining will be dynamic i.e. 123456/weqweqweqweqw and the last string will be /.

I tried:

var myRe = /\/type\/(.*)\//g

But this matches everything from /type/ to the end of the string.


Solution

  • Instead of repeating ., which will match anything, repeat anything but a space via \S+, so that only the URL part of the string will be matched:

    const str = 'this is extra data which i do not need /type/123456/weqweqweqweqw/ these are more extra data which i dont need /';
    console.log(str.match(/\/type\S+/));