-1

How to match some-blog-slug in all scenarios below:

  • /blog/some-blog-post-slug/whatever/anything (CASE 0)
  • /blog/some-blog-post-slug/whatever (CASE 1)
  • /blog/some-blog-post-slug/ (CASE 2)
  • /blog/some-blog-post-slug (CASE 3)

I'm trying: ^/\/blog\/([^\/]+)/

But it's not working at all.

enter image description here

I need to match some-blog-post so I can extract it from the string.

PS.: Sorry to post another REGEX question here on SO.

cbdeveloper
  • 27,898
  • 37
  • 155
  • 336

1 Answers1

2

Try out this code using exec() and substring() method .

var re = /\//g,
  str = "/blog/some-blog-post-slug/whatever/anything"; //You can try out all the cases you mentioned in the question . 
var arr = [];
while ((match = re.exec(str)) != null) {
  arr.push(match.index);
  console.log("match found at " + match.index);
}
console.log(arr)
if (arr.length >= 3) {
  var str = str.substring(arr[1] + 1, arr[2]);
  console.log(str)
} else {
  var str = str.substring(arr[1]);
  console.log(str)
}

Check my code in this LINK

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43