Reputation: 6246
I have these 2 patterns, to remove multiple hyphens or underscores in a replace, and replace them with just one, but seeing as there, basically the same, I was curious if I could combine them into one pattern.
url = url.replace(/([-]+)/g, '-');
url = url.replace(/([_]+)/g, '_');
I believe the actual pattern would just be /([-_])/g
, but I can't think how to tell if it should be replaced with a hyphen or underscore.
Upvotes: 0
Views: 48
Reputation: 89566
You can use a backreference:
url = url.replace(/([-_])\1+/g, '$1');
Upvotes: 3
Reputation: 67968
(-|_)+
Try this.Replace by $1
.See demo.
http://regex101.com/r/yA5iD9/7
Upvotes: -1
Reputation: 167192
Pipe (|
) operator is the OR function. Can you try this?
url = url.replace(/([-|_]+)/g, '-');
Upvotes: -1