Johannes
Johannes

Reputation: 337

Trying to find the regex for pretty URLs

I have a website structure like this:

/docs/one_of_the_resources/one-of-the-resources.html
/docs/a_complete_different_resource/a-complete-different-resource.html

I want to get rid of all sub-folders in the url and get this:

/one-of-the-resources.html
/a-complete-different-resource.html

Sub-folders should not be affected:

/docs/one_of_the_resources/assets/*

The folder name is always the same as the html file just dashes are swapped with underline and of course there is no suffix.

I'm using grunt-contrib-rewrite and grunt-connect.

Can't wrap my head around it. Is this even possible?

Upvotes: 1

Views: 212

Answers (1)

nu11p01n73R
nu11p01n73R

Reputation: 26667

You can use a negated character class

/\/[^/]+$/
  • [^/]+ Matches anything other than a /. The quantifier + ensures one or more characters.

  • $ Anchors the regex at the end of the string.

Regex Demo

Example

string = "/docs/one_of_the_resources/one-of-the-resources.html";
console.log(string.match(/\/[^/]+$/)[0]);
// => one-of-the-resources.html

Upvotes: 2

Related Questions