Alon
Alon

Reputation: 7758

How to make multiple regex replacements

I have this string of my domain:

www.my.domain.com

and I want my output to be:

my.domain

I do it currently like this:

str.replace("www.","").replace(".com","")

How can I make it with only one replacement instead of two?

Upvotes: 1

Views: 88

Answers (2)

QuentinUK
QuentinUK

Reputation: 3077

Here's what to do:-

str.replace(/^www\.|\.com$/g, '');

With beginning and end position search.

Will not go wrong with www.my.comedy-domain.com

Upvotes: 4

Peter Herdenborg
Peter Herdenborg

Reputation: 5972

Try this regexp:

str.replace(/www\.|\.com/g, '');

If you're not familiar with the syntax |means "or", making it match the patterns on both sides. \.since period otherwise means "any character". /gmakes the matching and replacing "global", i.e. processes all occurrences. If you want it to be case insensitive you can use /gi instead.

Upvotes: 6

Related Questions