A utility for converting a string into some styles: camelCase, PascalCase, kebab-case, snake_case, _underscore__case


Keywords
namestyle, namestyles, case, style, camel, pascal
License
MIT
Install
npm install name-styles@2.2.0

Documentation

name-styles

A utility to convert a string into some styles: camelCase, PascalCase, hyphen-case, snake_case, underscore_case with keeping leading underscores, etc.

Installation

Install by npm/yarn

npm add name-styles
yarn add name-styles

Quick Start

Normal styles

import {
    camel,
    pascal,
    hyphen,
    snake
} from "name-styles";

const s = "Hello Name-Styles";

camel(s);
// helloNameStyles

pascal(s);
// HelloNameStyles

hyphen(s);
// hello-name-styles

snake(s);
// hello_name_styles

Special underscore style

underscore style is similar to snake style, except that

  • it persists leading underscores
  • it does NOT merge middle underscores

Note that all spaces or hyphens should be tranformed to underscore, and leading ones are kept.

For example:

import { snake, underscore } from "name-styles";

const s = "-hello-world by--james";

snake(s);
// hello_world_by_james

underscore(s);
// _hello_world_by__james

On demand with babel-plugin-component

name-styles 2.0 re-orgnize the dist structure to fit the requirement of babel-plugin-component, so that you can import functions you actually need and the make the project smaller.

Of course, this need babel in your build orders.

You should install babel-plugin-component

npm install --save-dev babel-plugin-component

and use it in babel configuration (such as in .babelrc)

{
    "presets": [
        "env"
    ],
    "plugins": [
        [
            "component",
            [
                {
                    "libraryName": "mint-ui",
                }
            ]
        ]
    ]
}

If you want to use camel() and hyphen() only, you can import them exactly in code:

import { camel, hyphen } from "name-styles";

// ... do something

With babel-plugin-component, the build result should contain only definition of camel(), hyphen() and their dependencies.

Q&A

1. How to get a CONSTANT style result

You can transform a string to snake style, then change the result to UPPER case.

import { snake } from "name-styles";

const s = "this is a constant";
const CONSTANAT = snake(s).toUpperCase();
// THIS_IS_A_CONSTANT

2. How to get a sentence style result

The string in hyphen or snake style can be easily converted to sentence style

const { hyphen } from "name-styles";

const s = "ThisIsASentence";
const sentence = hyphen(s)
    .replace(/-/g, " ")
    .replace(/^./, ch => ch.toUpperCase());
// This is a sentence