1

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"

2
  • Why do you test for "and", when you say you want to test for "new"? Commented Aug 3, 2020 at 20:33
  • const newTitle = title.replace(/[^a-zA-Z0-9]+/g, '-').replace(/\band\b/g, "").toLowerCase();? Commented Aug 3, 2020 at 20:34

1 Answer 1

1

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)

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

Comments

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.