neoslo
neoslo

Reputation: 423

Javascript - Having multiple regex expressions to create url

I am attempting to use regex expressions to convert titles returning from an API into clean url structures. For example, my title "Most Sales for Retail & Consumer" I am attempting to convert it into most-sales-for-retail-consumer I would like my regex expression to remove any special characters, and the word "new" from its titles.

For example some titles return as "New Record of Sales" I would like to convert this into record-of-sales

I am approach this by using regex expressions but I am having an issue combining the expressions to have a 1 case fit all expression. I am attempting to create this in one expression if that is possible.

Here is what i've attempted which works for special characters:

const title = "Most Sales for Retail & Consumer"

const newTitle = title.replace(/([^a-zA-Z0-9]*|\s*)\s/g, '-').toLowerCase()
console.log(newTitle)

But when wanting to add a new expression to remove the word "new" if present in the title I am unable to succesfully while keeping the previous logic to remove special characters

const title ="New record of sales, & consumer"

const newTitle = title.replace(/\band\b/g, "").split(/ +/).join("-").toLowerCase()

console.log(newTitle)

Here is a snippet of my attempt to combine these two by using another .replace() after the first:

const title = "New Online Record & Sales" 

const newTitle = title.replace(/([^a-zA-Z0-9]*|\s*)\s/g, '-').replace(/\band\b/g, "")toLowerCase()

console.log(newTitle)

My expected outcome to have special characters remove while being able to remove the word "new"

Upvotes: 1

Views: 33

Answers (1)

trincot
trincot

Reputation: 350310

It will be easier if you first lower case your string, and then apply match:

const title = "New Online Record & Sales" 

const newTitle = title.toLowerCase()
                      .match(/[a-z0-9]+/g)
                      .filter(w => w !== "new")
                      .join("-");

console.log(newTitle)

Upvotes: 1

Related Questions