简体   繁体   中英

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. 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 (-)

The output should be all lower-cased letters

The output should not have any spaces.

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...

I'd rather just install https://www.npmjs.com/package/slugify which comes with a nice and configurable 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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