Extract number between slashes

2019-08-04 08:06发布

This is my setup:

var test = 
"http://tv.website.com/video/8086844/randomstring/".match(/^.+tv.website.com\/video\/(.*\d)/);

I want to extract the video id(8086844) and the regex does work, however when another digit is added after the "randomstring", it also matches the 8086844 + randomstring + other number.

What do I have to change in order to always get just the video id.

4条回答
淡お忘
2楼-- · 2019-08-04 08:32
var test = "http://tv.website.com/video/8086844/randomstring/8";
test = test.match(/^.+tv.website.com\/video\/(\d+)/);
console.log(test);
console.log(test[1]);

Output

[ 'http://tv.website.com/video/8086844',
  '8086844',
  index: 0,
  input: 'http://tv.website.com/video/8086844/randomstring/8' ]
8086844

You are almost there. We know that, its going to be only numbers. So instead of .*\d we are gathering only the digits and grouping them using parens.

查看更多
来,给爷笑一个
3楼-- · 2019-08-04 08:34

This is the simplest of all:

Use substr here

test.substr(28,7)

Fiddle

To extract out the id from your string test:We use substr(from,to)

查看更多
甜甜的少女心
4楼-- · 2019-08-04 08:42

Try this regex

/^.+tv.website.com\/video\/([\d]+)/

It will search every digit character after ...video\ word and then give all the concordant digits thereafter till any non-digit character comes

查看更多
5楼-- · 2019-08-04 08:46

The problem is the (.*\d) part, it looks for a greedy string ends with a digit, instead you need a continues series of digits after video/, it can be done via (\d+)

change it to

var test  = "http://tv.website.com/video/8086844/randomstring/dd".match(/^.+tv.website.com\/video\/(\d+)/)[1];
查看更多
登录 后发表回答