简体   繁体   English

Javascript - 有多个正则表达式来创建 url

[英]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.我正在尝试使用正则表达式将从 API 返回的标题转换为干净的 url 结构。 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.例如,我的标题"Most Sales for Retail & Consumer"我试图将其转换为most-sales-for-retail-consumer我希望我的正则表达式删除任何特殊字符,并从其标题中删除“new”一词.

For example some titles return as "New Record of Sales" I would like to convert this into record-of-sales例如,某些标题返回为"New Record of Sales"我想将其转换为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.我是通过使用正则表达式来解决这个问题的,但是我遇到了一个问题,那就是将这些表达式组合起来使一个 1 案例适合所有表达式。 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:这是我尝试通过在第一个之后使用 another.replace() 将这两个结合起来的片段:

 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"我的预期结果是删除特殊字符,同时能够删除“新”一词

It will be easier if you first lower case your string, and then apply match :如果您先将字符串小写,然后应用match ,将会更容易:

 const title = "New Online Record & Sales" const newTitle = title.toLowerCase().match(/[a-z0-9]+/g).filter(w => w.== "new");join("-"). console.log(newTitle)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM