Seth Duncan
Seth Duncan

Reputation: 1255

Regular Expression to match additional optional word

I have directory strings like so:

var list = ['/styles/portal/dragonfruit/green.scss',
'/styles/portal/version5/blue.scss',
'/styles/portal/version5/custom/company.scss',
'/styles/portal/version5/custom/industry.scss',
'/styles/portal/version5/custom/corporation.scss',
'/styles/portal/version5/admin/green.scss',
'/styles/portal/version5/admin/blue.scss'];

And I'd like to remove the starting styles/portal/version5/ portion from all strings, and optionally remove custom as well if it exists.

The output after processing this list would read:

/green.scss
/blue.scss
/company.scss
/industry.scss
/corporation.scss
/admin/green.scss
/admin/blue.scss

How do I optionally target the word match of custom when using a string.replace method?

So far I have:

var result = item.replace('styles/portal/version5/', '')

Upvotes: 0

Views: 26

Answers (1)

Code Maniac
Code Maniac

Reputation: 37755

You can use non captured group and make it optional

enter image description here

var list = ['/styles/portal/dragonfruit/green.scss','/styles/portal/version5/blue.scss','/styles/portal/version5/custom/company.scss','/styles/portal/version5/custom/industry.scss','/styles/portal/version5/custom/corporation.scss','/styles/portal/version5/admin/green.scss','/styles/portal/version5/admin/blue.scss'];

let final = list.map(v => v.replace(/^\/?styles\/portal\/version5(?:\/custom)?/, ''))

console.log(final)

Upvotes: 1

Related Questions