0

For example, i have these strings:

https://variant-color.com

http://variant-size.biz

http://variant-type.ca

I want to remove the URL's protocol, variant-, and domain using JS .replace() and regex, so the strings will be:

color

size

type

How to do it? I've tried it with the following code but it didn't work:

.replace("http://variant-","").replace("https://variant-","").replace(/^.[a-zA-Z]*/,"")

1 Answer 1

1

Well, there are multiple ways to do this. One of the easiest one could be using positive look behind approach with this regex:

/(?<=\-)\w+/gm

This will only match characters in your URL once they followed by - sign.

So the final output will be something like this:

const arr = [
  "https://variant-color.com",
  "http://variant-size.biz",
  "http://variant-type.ca"
]

const newArr = arr.flatMap(item => {
  return item.match(/(?<=\-)\w+/gm)
})

console.log(newArr)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks its work, but is there any similar method if we use jQuery?
@OzikJarwo I'm not sure what do you mean by jQuery here. But String#match is available through every javascript library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.