Coder Social home page Coder Social logo

slugify's Introduction

slugify

npm-version coveralls-status

var slugify = require('slugify')

slugify('some string') // some-string

// if you prefer something other than '-' as separator
slugify('some string', '_')  // some_string
  • Vanilla ES2015 JavaScript
    • If you need to use Slugify with older browsers, consider using version 1.4.7
  • No dependencies
  • Coerces foreign symbols to their English equivalent (check out the charMap for more details)
  • Works in the browser (window.slugify) and AMD/CommonJS-flavored module loaders

Options

slugify('some string', {
  replacement: '-',  // replace spaces with replacement character, defaults to `-`
  remove: undefined, // remove characters that match regex, defaults to `undefined`
  lower: false,      // convert to lower case, defaults to `false`
  strict: false,     // strip special characters except replacement, defaults to `false`
  locale: 'vi',      // language code of the locale to use
  trim: true         // trim leading and trailing replacement chars, defaults to `true`
})

Remove

For example, to remove *+~.()'"!:@ from the result slug, you can use slugify('..', {remove: /[*+~.()'"!:@]/g}).

  • If the value of remove is a regular expression, it should be a character class and only a character class. It should also use the global flag. (For example: /[*+~.()'"!:@]/g.) Otherwise, the remove option might not work as expected.
  • If the value of remove is a string, it should be a single character. Otherwise, the remove option might not work as expected.

Locales

The main charmap.json file contains all known characters and their transliteration. All new characters should be added there first. In case you stumble upon a character already set in charmap.json, but not transliterated correctly according to your language, then you have to add those characters in locales.json to override the already existing transliteration in charmap.json, but for your locale only.

You can get the correct language code of your language from here.

Extend

Out of the box slugify comes with support for a handful of Unicode symbols. For example the (radioactive) symbol is not defined in the charMap and therefore it will be stripped by default:

slugify('unicode ♥ is ☢') // unicode-love-is

However you can extend the supported symbols, or override the existing ones with your own:

slugify.extend({'☢': 'radioactive'})
slugify('unicode ♥ is ☢') // unicode-love-is-radioactive

Keep in mind that the extend method extends/overrides the default charMap for the entire process. In case you need a fresh instance of the slugify's charMap object you have to clean up the module cache first:

delete require.cache[require.resolve('slugify')]
var slugify = require('slugify')

Contribute

  1. Add chars to charmap.json
  2. Run tests npm test
  3. The tests will build the charmap in index.js and will sort the charmap.json
  4. Commit all modified files

Originally this was a vanilla javascript port of node-slug.
Note that the original slug module has been ported to vanilla javascript too.

slugify's People

Contributors

adrukh avatar ashotjanibekyan avatar avxkim avatar chmac avatar daniel1901 avatar energon7 avatar haltsir avatar httpstersk avatar iliazeus avatar itzlue avatar lorand-horvath avatar luisprmat avatar maxkrickl avatar neonerd avatar patricknausha avatar realityking avatar rohmanhm avatar roschaefer avatar roydigerhund avatar saadyousfi avatar simov avatar slavkobabic avatar stanley288 avatar stscoundrel avatar suecomarcus avatar sylvaindumont avatar trott avatar ugurh avatar xxzefgh avatar yegorshtonda 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  avatar  avatar  avatar  avatar  avatar

slugify's Issues

Should we add a strict mode that removes all special characters?

Somehow I expected this would be the default.

I love how this package coerces foreign symbols to their English equivalent.

The strict mode of my dreams would then remove any character that doesn’t match [a-zA-Z0-9-].

Achieving this using remove requires an exhaustive list which isn’t predictable.

What do you think? I could submit a PR if there is demand for this feature.

Slug error

Image
image

Input string:

Laravel 5.8: String và Array Helpers không được dùng nữa!

Result

Laravel-5.8:-String-va-Array-Helpers-khong-djuoc-dung-nua!

Expect string

Laravel-5.8:-String-va-Array-Helpers-khong-duoc-dung-nua!
``

multiple hyphens

slugify("developer @ Google", {
        lower: true,
        strict: true
      })

will return developer--google

still will cuase multiple hyphens

allowed items

Hi

it would be great to allow some special chars. For example I would like to allow '/' and tried to extend slugify with:

slugify.extend({'/':'/'})

without success. Any idea how to solve this?

is not removing ?

is not removiing the ? character from a variable. What am I doing wrong?

    let mySlug = req.body.title;
    slugify(mySlug, {
      replacement: '-',
      remove: /[?$*_+~.()'"!\-:@]/g,
      lower: true
    });

Parity between this package and the slug package

I'm looking to move from dodo/node-slug to this package, but there are a few discrepancies with the default charmap is making the migration a bit harder than anticipated.

Is there any opposition to adding some of the other characters from here? I'd be happy to put up a PR if you're okay with it!

Thanks!

Move char map to a separate file to improve package size

Having the char map on a separate file could help reducing bundle sizes for users that aren't making use of the standard char map. By using a bundler like webpack it's possible to skip bundling the to-be-created standard char-map file.

Duplicate seperators

Hi,

Currently when we have this string: 'Test - case' and we run slugify('Test - case')

We get:

'Test---case'. Is there a solution for this without stripping the spaces ourselves before running slugify?

Error when using slugify from TypeScript

I try to use slugify from TypeScript and get the following error:
Uncaught TypeError: slugify_1.default is not a function

Maybe something is wrong with the type definition?

import {default as slugify} from 'slugify';

slugify('test test');

does not slugify TitleCase

Not sure if this is within the scope of this function, but I was under impression that this was part of the usual process of slugification.

TitleCaseString is not converted to title-case-string, but rather returned as-is.

No spaces

I'm using slugify for subdomain names so I don't want spaces.

Using an empty string in the replacement option (replacement: '') doesn't work because the code '' || '-' on line 29 (https://github.com/simov/slugify/blob/master/slugify.js) will always default to '-'.

My current solution is to use new String('') instead. If this is the only solution, then it may be worth putting this as a note in the README.md file.

Thanks for the great work!

Override globally default config

Hi, is there a way to override the default configuration?
I want to have all the slugify strings get to lower by default and I don't want to specify them every time when calling the methods.

Thanks

Add remove URL predefine

A lot of times ids are used from strings that are going to be used in a URL. It would be great if we can have a predefine, like SLUGIFY.URL, so that it removes all the unsafe url characters.

Ability to create custom instances

It would be nice to be able to create individual instances of slugify like the following:

import slugify from 'slugify'

const urlify = slugify.create({ /* options */ })

This would be useful in larger projects where there may be slightly different use cases that are used often. This would be more preferable than remembering the regex each time, or writing a custom wrapper.

Cheers

Mention mongoose-slug-plugin use with slugify?

Using this package for generating slugs to use in URL's is probably fairly common. I'd suggest possibly putting a note in README such as...

Using Mongoose? Try mongoose-slug-plugin at https://github.com/ladjs/mongoose-slug-plugin!

Or something similar - the reason being is because a lot of Node.js users use MongoDB (Mongo is to Node.js what SQL is to Ruby imo). And the most popular ODM for MongoDB is Mongoose, therefore I figured it'd help out with confusion (considering there's dozens of poorly maintained, untested, and unpluggable slug helpers on NPM right now for Mongoose).

% character replaced by 'percent'

Hi all

When I use the code below :

function slugifyString(value) {
  return slugify(value, {
    replacement: '-',
    remove: /[&%]/g,
    lower: true
  })
}

console.log(slugifyString("aaa % bbb & ccc"))

I get "aaa-percent-bbb-and-ccc"

Why % and & are replaced by a string instead of being removed as set in the 'remove' parameter ?

Failing tets

Hello,

With your new version update we are getting the following error on our code:

  1. /tmp/app/src/server/lib/slugText.test.js should slugify a string with a % and replace with -percent

    expected 'test-string-with-100percent-in-it' to equal 'test-string-with-100-percent-in-it'

    • expected - actual

    -test-string-with-100percent-in-it
    +test-string-with-100-percent-in-it

    at Context. (src/server/lib/slugText.test.js:35:23)

    35 | expect(result).to.equal('test-string-with-100-percent-in-it');
    36 | });

Is it posible to take a look?

Common use case: replacing underscores with hyphens

As far as I can see, there is no way to replace underscores with hyphens?

let example1 = slugify('Uppercase_With_Underscores', {
      lower: true,
});
// outputs uppercase_with_underscores

Google Search Console recommends using Hyphens over Underscores:

Consider using punctuation in your URLs. The URL http://www.example.com/green-dress.html is much more useful to us than http://www.example.com/greendress.html. We recommend that you use hyphens (-) instead of underscores (_) in your URLs.

https://support.google.com/webmasters/answer/76329?hl=en

I am having to add my own RegEx to adjust the string:

let example1 = slugify('Uppercase_With_Underscores', {
      lower: true,
}).replace(/[_]/g, '-');
// outputs uppercase-with-underscores

Is there a better way using this library? Can you document it, as it's a common way to clean urls to be more readable.

Thanks!

Improvements for smaller size

  1. use .normalize("NFD") as suggested here https://twitter.com/LeaVerou/status/934590045708840960
  2. charMap can have only upper-case values and lower case values can be generated in the browser (on the fly)
  3. separate all transliteration tables in different files, so people would be able to pickup what languages to support. Like in lodash: import has from 'lodash/has';

PS Not connected to size: map().join("") is more memory efficient than .reduce()

Better examples

To figure which characters are replaced its needed to look into the tests / implementation.
What about adding 3 to 4 examples for strings that get slugified ?

Ç, Ü chars

Should be converted to C, U
{ "key": "ç", "value": "c" }, { "key": "Ù", "value": "U" },
But it turns

ue

Confusing readme.

The readme states

This port does not support unicode characters!

which doesn't seem true. Could the README clarify what the unicode support gap between slugify and slug is?

Note that the original slug module has been ported to vanilla javascript too.

This is useful information, but a selling point for slugify is that it does not require node-gyp to install, but slug does. That is probably worth mentioning. In fact, this is why I'm using slugify instead of slug (I'd rather not install python, make, g++, etc in my Docker image to install slug).

Using "remove" option might introduce untransliterated symbols

const slugify = require('slugify');
console.log(slugify('Аленький цветочек'));  // Alenkij-cvetochek
console.log(slugify('Аленький цветочек', {remove: /[()]+/g}));  // Alenьkij-cvetochek

That happens because slugify first removes the symbol, but then right away adds it back:

(charMap[ch] || ch).replace(options.remove || /[^\w\s$*_+~.()'"!\-:@]/g, '')
charMap['ь'] == ''
charMap['ь'] || 'ь' == 'ь'

default remove options doesn't work

because ^ means negated for the whole [] block

> '123!'.replace(/[^\w\s$*_+~.()'"!\-:@]/g, '')
'123!'

> '123!'.replace(/[\s$*_+~.()'"!\-:@]/g, '')
'123'

prevent to convert

how prevent this 2 char to dont convert to and96 andx2f ??????
for and / ? im using this setting : let slug = slugify( title , { replacement: '-', remove: /[*+~.()<>#$%^&_=/|`?'"!:@]/g,
lower: true,
strict: true,
});

Node versions support

Hi, in commit 325bcaa node requirements were changed from >=4.0.0 to ^4.0.0 which limited usage of node only to 4.. versions.

I am running node 7.10.0 on my machine and this breaks npm module installation.

error [email protected]: The engine "node" is incompatible with this module. Expected version "^4.0.0".
node --version
v7.10.0

Any particular reason for changing engine requirement?

Adding `strict` with a default of `false` should have been a major version change

Hi simov, thank you for your work on slugify--it is much appreciated.

We were using slugify in production with a remove regex and 1.4.0 broke our usage because the new strict option was added with a default of false, meaning our remove regex was no longer being applied.

For that reason I think it makes sense for the change as written to be a major version change. I'm not sure if you want to do anything now to mitigate this potential issue for other upgraders, but I'm sharing our experience in case it is useful to you. :)

Thanks again! ✨

Typescript declaration missing `locale` option

    | {
        replacement?: string;
        remove?: RegExp;
        lower?: boolean;
        strict?: boolean;
      }

This declaration should include locale option as the lib allow it.
I know that locale currently only support Vietnamese (vi), but we use it here, so please fix it.
Thank you.

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.