Giter VIP home page Giter VIP logo

slug's Introduction

Slugifies strings, even when they contain Unicode.

Make strings URL-safe.

  • Respects RFC 3986
  • No dependencies
  • Works in browser (window.slug) and AMD/CommonJS-flavoured module loaders
npm install slug

If you are using TypeScript you can install the accompanying types

npm install --save-dev @types/slug

Example

var slug = require('slug')
var print = console.log.bind(console, '>')

print(slug('i love unicode'))
// > i-love-unicode

print(slug('i love unicode', '_')) // If you prefer something else than `-` as separator
// > i_love_unicode

slug.charmap['♥'] = 'freaking love' // change default charmap or use option {charmap:{…}} as 2. argument
print(slug('I ♥ UNICODE'))
// > i-freaking-love-unicode

// To reset modifications to slug.charmap, use slug.reset():
slug.reset()
print(slug('I ♥ UNICODE'))
// > i-unicode

print(slug('Telephone-Number')) // lower case by default
// > telephone-number

print(slug('Telephone-Number', {lower: false})) // If you want to preserve case
// > Telephone-Number

// We try to provide sensible defaults.
// So Cyrillic text will be transliterated as if it were Russian:
print(slug('маленький подъезд'))
// > malenkij-poduezd

// But maybe you know it's Bulgarian:
print(slug('маленький подъезд', { locale: 'bg' }))
// > malenykiy-podaezd

// To set the default locale:
slug.setLocale('bg')
print(slug('маленький подъезд'))
// > malenykiy-podaezd

print(slug('unicode is ☢'))
// > unicode-is

slug.extend({'☢': 'radioactive'})
print(slug('unicode ♥ is ☢'))
// > unicode-is-radioactive

// slug.extend() modifies the default charmap for the entire process.
// If you need to reset charmap, multicharmap, and the default locale, use slug.reset():

slug.reset()
print(slug('unicode ♥ is ☢'))
// > unicode-is

// Custom removal of characters from resulting slug. Let's say that we want to
// remove all numbers for some reason.
print(slug('one 1 two 2 three 3'))
// > one-1-two-2-three-3
print(slug('one 1 two 2 three 3', { remove: /[0-9]/g }))
// > one-two-three

options

// options is either object or replacement (sets options.replacement)
slug('string', [{options} || 'replacement']);
slug.defaults.mode ='pretty';
slug.defaults.modes['rfc3986'] = {
    replacement: '-',      // replace spaces with replacement
    remove: null,          // (optional) regex to remove characters
    lower: true,           // result in lower case
    charmap: slug.charmap, // replace special characters
    multicharmap: slug.multicharmap, // replace multiple code unit characters
    trim: true,             // trim leading and trailing replacement chars
    fallback: true          // use base64 to generate slug for empty results
};
slug.defaults.modes['pretty'] = {
    replacement: '-',
    remove: null,
    lower: false,
    charmap: slug.charmap,
    multicharmap: slug.multicharmap,
    trim: true,
    fallback: true
};

Differences between slug and slugify packages

Here are some key differences between this package and slugify.

  • Defaults: slug has the lower option enabled by default, lowercasing all slugs ('On SALE' becomes 'on-sale').
    slugify has the lower option disabled by default ('On SALE' becomes 'On-SALE').
  • Symbols: slug removes unrecognized symbols ('$100' becomes '100', '<5' becomes '5', etc.).
    slugify maps them to words ('$100' becomes 'dollar100', '<5' becomes 'less5', etc.).
  • Empty Output: slug will return a short, predictable hash (' ' becomes 'icag' and '🎉' becomes '8joiq').
    slugify will return an empty string (' ' and '🎉' become '').
  • Stability: slug is planning a new release that will drop support for CommonJS and only support ESM modules.
    slugify will continue to support CommonJS and is likely to remain stable for the foreseeable future.

Playground

A (painfully minimal) web playground is available at https://trott.github.io/slug/. It doesn't allow you to specify options, so it's utility is minimal. Pull requests welcome to add the ability to specify options.

There is also a (similarly minimal) CLI tool available via npx slug. As with the web playground, it doesn't allow you to specify options, so it's utility is minimal.

slug's People

Contributors

a-tokyo avatar antonipelka avatar bertrandda avatar bitdeli-chef avatar curtisgibby avatar dependabot-preview[bot] avatar dependabot[bot] avatar dodo avatar dominhhai avatar dominykas avatar duckyb avatar gromov-io avatar jaketrent avatar laurent22 avatar linusu avatar mitica avatar niftylettuce avatar prozacgod avatar semantic-release-bot avatar setchy avatar soviut avatar srtech avatar trott avatar vesln avatar wyoumans avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

slug's Issues

Add option to remove all transliteration

Hi!

Please could you add an option to disable transliteration? It's not always appropriate or user friendly for certain languages to have all their URL's be converted "into English".

Thank you

Custom character map replacement changes uppercase characters to lowercase

I was trying to replace a Unicode character with some uppercase characters. But if the lowercase mode is toggled on, it also changes the character map replacement to lowercase.

For example
slug.extend({ "’": "%25E2%2580%2599" });

changes to %25e2%2580%2599

Anyway to maintain the uppercase in character map replacement without toggling the lowercase mode?

Opt-out of base64 fallback

Hey, first of all, really nice library, great job!

Wouldn't it be a better way to have base64 fallback as an option? Then it would be open for extension and if someone needed other encoding or no slug at all they could just add it on top of the library.

I would benefit from "no-slug" option in my project but I see that the underlying slugify function is encapsulated. If there was an easy way to access it then it would also be much nicer.

Originally posted by @antonipelka in #27 (comment)

Typo in example?

Is this a typo in the example? Why does this not result into i-unicode?

slug/README.md

Lines 37 to 40 in a952db1

// To reset modifications to slug.charmap, use slug.reset():
slug.reset()
print(slug('I ♥ UNICODE'))
// > i_unicode

Simple algorithm to detect ambiguous situations

It seems that the character đ may be transliterated in at least three different ways:

Perhaps the algorithm for this (and other characters that can be transliterated in multiple ways) might be:

  • If the input string contains no ambiguous characters (such as đ), use the current algorithm.
  • Otherwise, we need to figure out the language, Naive first-pass implementation will be:
    • If the input string consists entirely of characters that are valid in one of the languages but not any of the others, use that language's transliteration.
    • Otherwise, take the list of possible languages (that is, languages for which all characters in the string are valid), and select the language with the most native speakers. (I believe in this case, the ordering would be Vietnamese, Serbian, Macedonian.) That will at least hopefully tend to guess correctly.
    • If there are no languages that can contain all the characters, use the transliteration from the language with the most native speakers (in this case, Vietnamese).

This can be iterated on to improve it, but something simple like this is probably better than what we have now (which is "we have Serbian, so that's what we're using"). And we probably don't need to go full machine-learning model on this.

🐛 `-` dash instances are omitted when `replacement` is set to `_` underscore.

When providing the replacement as _ the - instances are wrongfully omitted.

slug('arabic-english translator') // "arabic-english-translator"
slug('arabic-english translator', { replacement: '_' }) // "arabicenglish_translator" (this is wrong, should be "arabic-english_translator")

expected behavior:

slug('arabic-english translator', { replacement: '_' }) // "arabic_english_translator"

No method to 'unslug' a string

This may be a feature suggestion, or I may be missing something entirely.
There should be a way to reverse the slug method and revert back to the string before it has been made into a slug.
Example:

const myStr = "Hello World!";  // Hello World!
const mySlug = slug(myStr);   // hello-world
...
console.log(unslug(mySlug));  // out: hello world

Although, I see that there may be some cases where data is lost in translation such as the capital letters and exclamation point. There is no way to tell what the previous string was before, but if you already are storing strings in all lower case with no capital letters it may be useful to have a method to revert any changes the slug() method does. But it must be noted that it is not fully reliable in all cases.

Let me know what you think.

Greek theta incorrectly maps to 8

I'm not sure if this was a conscious decision based on appearance, and I am not Greek and not an expert, but I do have some Greek content, and I believe that the Greek letter theta (Θ) would be best transliterated to Th. With the lowercase θ being th.

A comparison to simov/slugify in the README would be very helpful

This project and https://github.com/simov/slugify are the first two results when you search either npm slug or npm slugify. I've been trying to compare the projects, but the features, the examples and the configuration all seem very similar. Both packages are updated regularly and you even contribute to both of them; which is awesome, but doesn't make it any easier to choose.

This is me right now.

image

It would be great if there was a comparison in the README explaining any key differences to be aware of so anyone stumbling on both can tell them apart at a glance.

Default locale?

Is it possible to add option for default locale?

For example if running website completely in german language it makes sense to use that locale by default without specifying it every time.

Thanks!

Explain transition from dodo/node-slug to trott/slug

Could you maybe add an info inside the readme to explain the transition from dodo to you? I could not find any info here and thought it would make sense, because of the missing possibility to archive the node-slug repository.

Missing support for ES5 compiled apps

Me and my team are trying to support IE11 in our Angular 8 application, but unfortunately this library breaks vendor.js because of the arrow function syntax.

Screenshot of the problem

img

Minimal reproduction App

slug-error-minimal.zip

Running the reproduction:

  1. Unzip
  2. run npm i
  3. run ng serve
  4. open IE11

A fix for this would be greatly appreciated!

Playground?

It’d be nice if slug could be tried out without installing it. Two options are:

  • A web page (a “playground”) hosted via GitHub pages.
  • A "bin" script that can be executed via npx.

Can removing trailing replacement characters be optional? This was a breaking change for us as we use `slugify` for automatically validating and cleaning up urls being typed into a text field.

Can removing trailing replacement characters be optional? This was a breaking change for us as we use slugify for automatically validating and cleaning up urls being typed into a text field.
Previously, a user could type in a-url-with-replacement-characters one character at a time in a text field and get back a-url-with-replacement-characters.
However, since the "-" characters will automatically get cleared when typing now (aka, when it's trailing like a-url-), it comes out to aurlwithspaces.

Originally posted by @davidlukerice in simov/slugify#112 (comment)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.