TMH
TMH

Reputation: 6246

Is there anyway to combine these 2 regex patterns into one?

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

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89566

You can use a backreference:

url = url.replace(/([-_])\1+/g, '$1');

Upvotes: 3

vks
vks

Reputation: 67968

(-|_)+

Try this.Replace by $1.See demo.

http://regex101.com/r/yA5iD9/7

Upvotes: -1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167192

Pipe (|) operator is the OR function. Can you try this?

url = url.replace(/([-|_]+)/g, '-');

Upvotes: -1

Related Questions