简体   繁体   English

正则表达式 | 应用函数式编程将字符串转换为 URL Slug

[英]Regular Expression | Apply Functional Programming to Convert Strings to URL Slugs

Question问题

Fill in the urlSlug function so it converts a string title and returns the hyphenated version for the URL. You can use any of the methods covered in this section, and don't use replace.填写 urlSlug function,以便它转换字符串标题并返回 URL 的带连字符的版本。您可以使用本节介绍的任何方法,但不要使用替换。 Here are the requirements:以下是要求:

The input is a string with spaces and title-cased words输入是一个包含空格和标题大写单词的字符串

The output is a string with the spaces between words replaced by a hyphen (-) output 是一个字符串,单词之间的空格替换为连字符 (-)

The output should be all lower-cased letters output应该全部是小写字母

The output should not have any spaces. output 不应有任何空格。

My Solution我的解决方案

 var globalTitle = " Winter Is Coming"; function urlSlug(title) { let regex = /(?<?\s)\s(..\s)/g let a = title.toLowerCase().trim();split(regex).join('-') return a; } console.log(urlSlug(globalTitle))

My Question我的问题

I want to use positive and negative look aheads / look behinds to resolve this problem: my particular issue seems to be if the string has more than one space.我想使用正面和负面的前瞻/后视来解决这个问题:我的特殊问题似乎是字符串是否有多个空格。 What changes can be made to make this work?可以进行哪些更改才能使这项工作正常进行?

You can use quantifier + which means one or more您可以使用量词+表示一个或多个

 var globalTitle = " Winter Is Coming"; function urlSlug(title) { let regex = /\s+/g let a = title.toLowerCase().trim().split(regex).join('-') return a; } console.log(urlSlug(globalTitle))

It doesn't seem like you need to split the string into an array.您似乎不需要将字符串拆分为数组。

 const slugify = (input = '') => input.trim().replace(/\s+/g, '-').toLowerCase(); console.log( slugify(" Winter Is Coming "), );


PS: these operations are very error prone to be done manually, as there are tons of edge cases to be handled... PS:这些操作很容易手动完成,因为有大量的边缘情况需要处理......

I'd rather just install https://www.npmjs.com/package/slugify which comes with a nice and configurable API .我宁愿只安装https://www.npmjs.com/package/slugify ,它带有一个不错且可配置的 API

 console.log( slugify(" Winter is Coming", { lower: true }), );
 <script src="https://cdn.jsdelivr.net/npm/slugify@1.4.0/slugify.js"></script>

It can be answered without using regex.无需使用正则表达式即可回答。 With the filter method, there is no need to trim the method.使用过滤方法,不需要修剪方法。 Using a filter can be removed spaces from the list.使用过滤器可以从列表中删除空格。 More information about filter can be found https://www.w3schools.com/jsref/jsref_filter.asp有关过滤器的更多信息可以找到https://www.w3schools.com/jsref/jsref_filter.asp

  function urlSlug(urlTitle) {
   .split(" ")
   .filter(substr => substr !== "")
   .join("-")
   .toLowerCase();
  return urlTitle;
  }

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

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