Home > Back-end >  How can I extract numbers between slashes in javascript
How can I extract numbers between slashes in javascript

Time:10-15

I have a strings with this pattern,

ver1.1/hello/12345/bar -> extract 12345
world/098767123/foo   -> extract 098767123
ver1.2344/foo/78687115/ -> extract 78687115

I used /\d /g or /\d /, but didn't have luck that always ver numbers come too. How can I extract numbers which does not have any char and between slashes?

CodePudding user response:

Use a capturing group to capture only the numbers between slashes: \/(\d )\/

console.log("ver1.1/hello/12345/bar".match(/\/(\d )\//))

CodePudding user response:

You can use a capture group for this, e.g.:

var regex = /\/(\d )\//;
var string = "ver1.2344/foo/78687115/";
var match = string.match(regex);
if (match) {
    console.log(match[1]);
}

You can also use /(?:\/|^)(\d )(?:\/|$)/ for numbers that happen at the beginning or end of the string. This just has two non-capturing groups that say "match / or the beginning/end"

  • Related