javascript – Regex expression to replace special characters except first and last character found

I’d like to remove every special character from a string identifier and replace them with hyphens so it can be URL friendly.

This is part of Sitefinity CMS URL configuration, meaning that every time I create an item, it gets the title of it and generates a URL slug based on the regex expression I provide.

So I can only use ONE regex expression, and ONE substitution text, since it is added in Sitefinity’s CMS URL configuration fields.

I can’t use code or use regex in multiple steps.

So, for example, if I have the following title string:
Infographic phishing's awareness and $prevention (updated)

I’d like it to transform to:
infographic-phishing-awareness-and-prevention-updated

I’m able to do so, except prevent adding a hyphen at the start or end.

So far I have this regex expression: /((?:[^\w-]|_)+)/g
With the substitution being “-“

But this one adds a hyphen at the end as well, and ends up b
infographic-phishing-awareness-and-prevention-updated-

Is there a way I can replace the last special characters at the end of the string with an empty space?

Read more here: Source link