The ultimate JavaScript string library

Overview

Voca JavaScript library logo

travis build code coverage npm package

Voca is a JavaScript library for manipulating strings. https://vocajs.com

v.camelCase('bird flight');              // => 'birdFlight'
v.sprintf('%s costs $%.2f', 'Tea', 1.5); // => 'Tea costs $1.50'
v.slugify('What a wonderful world');     // => 'what-a-wonderful-world'

The Voca library offers helpful functions to make string manipulations comfortable: change case, trim, pad, slugify, latinise, sprintf'y, truncate, escape and much more. The modular design allows to load the entire library, or individual functions to minimize the application builds. The library is fully tested, well documented and long-term supported.

Features

  • Provides the complete set of functions to manipulate, chop, format, escape and query strings
  • Includes detailed, easy to read and searchable documentation
  • Supports a wide range of environments: Node.js 0.10+, Chrome, Firefox, Safari 7+, Edge 13+, IE 9+
  • 100% code coverage
  • No dependencies

Documentation

See the complete documentation at https://vocajs.com

Usage

Voca can be used in various environments.

Node.js, Rollup, Webpack, Browserify

Voca JavaScript library supports Node.js, Rollup, Webpack, Browserify

Install the library with npm into your local modules directory:

npm install voca

CommonJS modules

Then in your application require the entire library:

const v = require('voca');
v.trim(' Hello World! ');            // => 'Hello World'
v.sprintf('%d red %s', 3, 'apples'); // => '3 red apples'

Or require individual functions:

const words = require('voca/words');
const slugify = require('voca/slugify');
words('welcome to Earth'); // => ['welcome', 'to', 'Earth']
slugify('caffé latté');    // => 'caffe-latte'

ES2015 modules

Voca is compatible with ES2015 modules to import the entire library:

import voca from 'voca';
voca.kebabCase('goodbye blue sky'); // => 'goodbye-blue-sky'

Or import individual functions:

import last from 'voca/last';
last('sun rises', 5); // => 'rises'

Browser

Voca JavaScript library supports Chrome, Firefox, Safari, Edge, Internet Explorer

Load the UMD builds directly into browser's web page:

<script src="voca.js" type="text/javascript"></script>

Then a global variable v is exposed for the entire library:

<script type="text/javascript">
  v.last('wonderful world', 5); // => 'world'
</script>

Functions

Manipulate Query Chop Case Index
v.insert v.endsWith v.charAt v.camelCase v.indexOf
v.latinise v.includes v.codePointAt v.capitalize v.lastIndexOf
v.pad v.isAlpha v.first v.decapitalize v.search
v.padLeft v.isAlphaDigit v.graphemeAt v.kebabCase Escape
v.padRight v.isBlank v.last v.lowerCase v.escapeHtml
v.repeat v.isDigit v.prune v.snakeCase v.escapeRegExp
v.replace v.isEmpty v.slice v.swapCase v.unescapeHtml
v.replaceAll v.isLowerCase v.substr v.titleCase Strip
v.reverse v.isNumeric v.substring v.upperCase v.stripBom
v.reverseGrapheme v.isString v.truncate Split v.stripTags
v.slugify v.isUpperCase Count v.chars
v.splice v.matches v.count v.codePoints
v.tr v.startsWith v.countGraphemes v.graphemes
v.trim Format v.countSubstrings v.split
v.trimLeft v.sprintf v.countWhere v.words
v.trimRight v.vprintf v.countWords
v.wordWrap

Bug reports

For bug reports, documentation typos or feature requests feel free to create an issue.
Please make sure that the same problem wasn't reported already.

For general usage questions please ask on StackOverflow.

Contributing

Contribution is welcome!

  • Create a pull request containing bug fixes or new features. Include unit tests and keep the code coverage report near 100% 😎
  • Propose new functions, improvements, better documentation

See more details in Contributing guide.

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.

Author

Dmitri Pavlutin
Dmitri Pavlutin
Personal blog
Email

License

Licensed under MIT

Comments
  • New way of string formatting

    New way of string formatting

    Hello!

    What do you think about idea of implementing such formatting?

    If we would name this function format, then here are some examples of how it would work:

    v.sformat('{}, {}, {}', 0, 1, 2); => '0, 1, 2' v.sformat('{0}, {0}, {1}, {2}, {3}', 1, 2, 3, 5); => '1, 1, 2, 3, 5' v.format('{name}: {a}+{b}={c}', {name: 'sum', a: 1, b: 2, c:3}); => 'sum: 1+2=3'

    There would be also possibility to pass function to format.

    If you think this is a good idea, then I would implement it in the coming days :smile:

    enhancement 
    opened by SzymonStankiewicz 9
  • explorer support

    explorer support

    Hi! I tried the voca.js on explorer v11 and it crashed.

    I'm not an expert in javascript but I managed to make it work by adding a few lines. Maybe it could be useful to others?

    Modifies:

    At the very beginning of the file:

    //object.keys support
    if (!Object.keys) {
      Object.keys = function(obj) {
        var keys = [];
        for (var i in obj) {
          if (obj.hasOwnProperty(i)) {
          keys.push(i);
        }
      }
     return keys;
      };
    }
    
    //object.values support
    if (!Object.values) {
    
    Object.values = function(obj) {
    
    var res = [];
        for (var i in obj) {
            if (obj.hasOwnProperty(i)) {
                res.push(obj[i]);
            }
        }
        return res;
      };
    }
    
    //Array.foreach support
    if (!Array.prototype.forEach) {
        Array.prototype.forEach = function(fn, scope) {
            for(var i = 0, len = this.length; i < len; ++i) {
                fn.call(scope, this[i], i, this);
            }
        }
    }
    
    //Array.isArray support
    if (!Array.isArray) {
        Array.isArray = function(item) {
          if(item instanceof Array){return true;}
          return false;
        }
    }
    
    //bind support
    if (!Function.prototype.bind) {
      Function.prototype.bind = function(oThis) {
        if (typeof this !== 'function') {
          // closest thing possible to the ECMAScript 5
          // internal IsCallable function
          throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
        }
    
        var aArgs   = Array.prototype.slice.call(arguments, 1),
            fToBind = this,
            fNOP    = function() {},
            fBound  = function() {
              return fToBind.apply(this instanceof fNOP && oThis
                     ? this
                     : oThis,
                     aArgs.concat(Array.prototype.slice.call(arguments)));
            };
    
        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();
    
        return fBound;
      };
    }
    
    (function (global, factory) { 
    [...]
    

    And then the function isNil

    function isNil(value) {
        return value === undefined || value === null || value === '';
    }
    

    Now it works.

    opened by Kreider186 8
  • titleCase behaviour with prime/apostrophe

    titleCase behaviour with prime/apostrophe

    Expected behavior :smile_cat:

    v.titleCase("professor's office")
    'Professor\'s Office'
    

    Actual behavior :crying_cat_face:

    v.titleCase("professor's office")
    'Professor\'S Office'
    

    Node version: 8.1.4

    Are there situations that I'm missing here where a letter after a prime/apostrophe should be capitalized? The same behaviour occurs with real/smart quotes ( as opposed to ') as well

    > v.titleCase("professor’s office")
    'Professor’S Office'
    
    enhancement 
    opened by DJTB 8
  • Changes to Repeat and Reverse

    Changes to Repeat and Reverse

    Description

    Repeat: Removed while loop, used repeat method of String.prototype to improve readability Reverse: Changed function to increase time complexity from O(3n) to O(n)

    Check List

    • [X] All test passed
    • [ ] Added test to ensure correctness
    opened by kiraknowsbest 6
  • Strip HTML from Text

    Strip HTML from Text

    Awesome library, would have a suggestion. v.stripHtml(htmlTagArray = [''])

    If any htmlTag is given within the array the strip function is limited to them otherwise the function removes all html tags.

    enhancement 
    opened by nhaberl 6
  • issue w/ prune

    issue w/ prune

    Welcome to Voca's GitHub repo!

    Expected behavior :smile_cat:

    expect(v.prune('YATTA, ', 6, '')).toEqual('YATTA,');
    

    Actual behavior :crying_cat_face:

    expect(v.prune('YATTA, ', 6, '')).toEqual('YATTA'); // the string is missing the `,` at the end
    

    Steps to reproduce :construction_worker:

    https://github.com/mattiaerre/china-musk/blob/master/src/store/prune.test.js

    Technical details: :wrench:

    Browser/OS type: macOS Mojave Node version: v10

    thanks so much, -Mattia

    opened by mattiaerre 4
  • Voca doesn't handle complex characters like కృష్ణ

    Voca doesn't handle complex characters like కృష్ణ

    Welcome to Voca's GitHub repo!

    Expected behavior :smile_cat:

    v.graphemes("కృష్ణ") should return (2) ["కృ", "ష్ణ"] v.countGraphemes("కృష్ణ") should return 2

    Actual behavior :crying_cat_face:

    v.graphemes("కృష్ణ") returns (5) ["క", "ృ", "ష", "్", "ణ"] v.countGraphemes("కృష్ణ") returns 5

    Steps to reproduce :construction_worker:

    v.graphemes("కృష్ణ") v.countGraphemes("కృష్ణ")

    Technical details: :wrench:

    Browser/OS type: n/a Node version: n/a

    opened by kotpal 4
  • Feature Suggestion: Title Case

    Feature Suggestion: Title Case

    Feature Suggestion

    Convert a string to title case.

    Examples

    v.titleCase('hello world')
    // => 'Hello World
    v.titleCase('Hello world')
    // => 'Hello World
    v.titleCase('hello World')
    // => 'Hello World
    

    Implentation Suggestions

    This SO question has many suggestions.

    The top answer uses string.replace() with regex:

    function toTitleCase(str) {
      return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    }
    

    Not sure about the coverage of all cases.

    Options

    In formal title case, words like 'a', 'it', 'of', etc. are ignored (not capitalized). Consider this as an option. v.titleCase(subject, allWords)

    v.titleCase('this is a title of great proportions', true);
    // => 'This Is A Title Of Great Proportions'
    v.titleCase('this is a title of great proportions', false);
    // => 'This is a Title of Great Proportions'
    
    enhancement 
    opened by alanqthomas 4
  • Feature Request : Function for finding all possible combinations of given string.

    Feature Request : Function for finding all possible combinations of given string.

    For e.g. If the input is "wxyz" then the output of the string should be ['w','wx','wxy','wxyz','wxz','wy','wyz','wz','x','xy','xyz','xz','y','yz','z']

    wontfix 
    opened by mahesh1996 4
  • Default regex for words treats numbers as individual words

    Default regex for words treats numbers as individual words

    I am unsure if this is behavior is intended or not but if there is a number that is part of word or acronym it is broken out as a separate word.

    Expected behavior:

    v.words('What Is The Best MACD Indicator for MT4?') (8) ["What", "Is", "The", "Best", "MACD", "Indicator", "for", "MT4"]

    v.countWords('What Is The Best MACD Indicator for MT4?') 8

    Current behavior: v.words('What Is The Best MACD Indicator for MT4?') (9) ["What", "Is", "The", "Best", "MACD", "Indicator", "for", "MT", "4"]

    v.countWords('What Is The Best MACD Indicator for MT4?') 9

    I realize I could come up with my own regex to solve this issue but the default regex works really well besides this one scenario which doesn't seem intended.

    I am using Voca 1.4.0

    wontfix 
    opened by IMN-MichaelL 2
  • Bump acorn from 5.7.3 to 5.7.4

    Bump acorn from 5.7.3 to 5.7.4

    Bumps acorn from 5.7.3 to 5.7.4.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 2
  • Fix doc typo in `const`

    Fix doc typo in `const`

    Related issue

    None

    Description

    The file at src/helper/number/const.js had a typo in the JSdoc comment. It said "save integer" instead of "safe integer"

    Check List

    • [x] All test passed
    • [ ] Added test to ensure correctness
    opened by Rudxain 0
  • Any plans to handle encodings?

    Any plans to handle encodings?

    I think this library should include functions to convert Strings to TypedArrays and viceversa, with the option to interpret as UTF-8 or UTF-16 depending on use case. So if a string is to be interpreted as UTF-8, the corresponding TypedArray should be a Uint8Array, otherwise UTF-16 is used and a Uint16Array of code-units is returned. If an arbitrary TypedArray is provided, it'll be read as a string of octets, and those octets will be converted to a string depending on the chosen encoding. UTF-16 has endianess and BOMs, so a function that handles implicit and explicit endianess would be slightly more complicated.

    Another thing related to encodings are binary-to-text encodings like Hexadecimal, base64, base85, etc. JS already has base64 support with atob and btoa, but hex and base85 are missing, which could be provided by this library.

    I don't know if these features should be added to this library because Voca seems to be intended for high-level (not low-level) use cases, and adding base85 support would be pointless because it's rarely used. Any constructive criticism is appreciated

    opened by Rudxain 1
  • Optimization Interests?

    Optimization Interests?

    Scripts are cool for frontend. But serverside needs performance.

    Chaining the string methods practically causes reloops per chain.

    How about synthesizing methods together for one loop?

    Starting the project in a few a days.

    opened by Neur0plasticity 0
  • Reverse camelcase?

    Reverse camelcase?

    I like Voca better than the alternatives, but I can't see how you would convert camelcase into words. In other libs it's called .humanize

    For example:

    "camelCase" -> "camel case"

    opened by jsodeman 1
  • Error in function getGlobalObject in ./node_modules/voca/index.js:3595

    Error in function getGlobalObject in ./node_modules/voca/index.js:3595

    Welcome to Voca's GitHub repo!

    Expected behavior :smile_cat:

    Importing the library should not throw an exception.

    Actual behavior :crying_cat_face:

    Following exception is thrown:

    global is not defined

    Error in function getGlobalObject in ./node_modules/voca/index.js:3595
    
     3593 |   if (typeof global === 'object' && global.Object === Object) {
     3594 |     // NodeJS global object
    > 3595 |     globalObject$1 = global;
    

    Steps to reproduce :construction_worker:

    This seems to be an issue using voca in the latest major update of Gatsby (v3), or perhaps Webpack? From what I can gather, voca is initialising the global object using "global" (ie NodeJS instance) even though this is a browser instance, I don't understand why it would be entering that if statement

    Technical details: :wrench:

    Browser/OS type: Chrome/ Ubuntu 20 Node version: v12.21.0

    opened by stephan-swiftcom 0
  • fix:title-abbreviations problem

    fix:title-abbreviations problem

    Related issue

    #50 Title Abbreviations

    Description

    Add another input in titleCase function named preserveUpperCase

    Check List

    • [x] All test passed
    • [x] Added test to ensure correctness
    opened by fatteme 2
Releases(v1.4.0)
Owner
Dmitri Pavlutin
I help developers understand JavaScript and React.
Dmitri Pavlutin
String manipulation helpers for javascript

The stable release documentation can be found here https://epeli.github.io/underscore.string/ Underscore.string Javascript lacks complete string manip

Esa-Matti Suuronen 3.4k Dec 25, 2022
Extra JavaScript string methods.

string.js string.js, or simply S is a lightweight (< 5 kb minified and gzipped) JavaScript library for the browser or for Node.js that provides extra

JP Richardson 1.8k Dec 17, 2022
easier than regex string matching patterns for urls and other strings. turn strings into data or data into strings.

url-pattern easier than regex string matching patterns for urls and other strings. turn strings into data or data into strings. This is a great little

null 562 Jan 5, 2023
Javascript URL mutation library

URI.js About Understanding URIs Documentation jQuery URI Plugin Author Changelog IMPORTANT: You may not need URI.js anymore! Modern browsers provide t

Medialize 6.2k Dec 30, 2022
:fishing_pole_and_fish: A library that allows you to access the text selected by the user

selecting A library that allows you to access the text selected by the user. Instalation To install Selecting, execute: npm install selecting Or Bow

Evandro Leopoldino Gonçalves 87 Nov 17, 2022
A robust HTML entity encoder/decoder written in JavaScript.

he he (for “HTML entities”) is a robust HTML entity encoder/decoder written in JavaScript. It supports all standardized named character references as

Mathias Bynens 3.2k Dec 27, 2022
Multiline strings in JavaScript

multiline Multiline strings in JavaScript No more string concatenation or array join! Use ES2015 template literals instead whenever possible. Before c

Sindre Sorhus 1.4k Dec 30, 2022
Lightweight URL manipulation with JavaScript

domurl 2.x (former jsurl) Lightweight URL manipulation with JavaScript for both DOM and server JavaScript. Goal To have a convenient way working with

Mykhailo Stadnyk 511 Dec 28, 2022
sprintf.js is a complete open source JavaScript sprintf implementation

sprintf-js sprintf-js is a complete open source JavaScript sprintf implementation for the browser and Node.js. Note: as of v1.1.1 you might need some

Alexandru Mărășteanu 2k Jan 4, 2023
The ultimate JavaScript string library

Voca is a JavaScript library for manipulating strings. https://vocajs.com v.camelCase('bird flight'); // => 'birdFlight' v.sprintf('%s co

Dmitri Pavlutin 3.5k Dec 20, 2022
⚡️The Fullstack React Framework — built on Next.js

The Fullstack React Framework "Zero-API" Data Layer — Built on Next.js — Inspired by Ruby on Rails Read the Documentation “Zero-API” data layer lets y

⚡️Blitz 12.5k Jan 4, 2023
Convert some JavaScript/TypeScript code string into a .d.ts TypeScript Declaration code string

convert-to-dts Converts the source code for any .js or .ts file into the equivalent .d.ts code TypeScript would generate. Usage import { convertToDecl

Lily Scott 11 Mar 3, 2022
v8n ☑️ ultimate JavaScript validation library

The ultimate JavaScript validation library you've ever needed. Dead simple fluent API. Customizable. Reusable. Installation - Documentation - API Intr

Bruno C. Couto 4.1k Dec 30, 2022
🚀 The ultimate library for managing multi-channel notifications with a single API.

?? The ultimate library for managing multi-channel notifications with a single API.

Notifire 16.3k Jan 4, 2023
Ultimate calendar for your React app.

React-Calendar Ultimate calendar for your React app. Pick days, months, years, or even decades Supports range selection Supports virtually any languag

Wojciech Maj 2.8k Dec 27, 2022
The ultimate generator based flow-control goodness for nodejs (supports thunks, promises, etc)

co Generator based control flow goodness for nodejs and the browser, using promises, letting you write non-blocking code in a nice-ish way. Co v4 co@4

TJ Holowaychuk 11.8k Jan 2, 2023
The ultimate solution for populating your MongoDB database.

Mongo Seeding The ultimate solution for populating your MongoDB database ?? Define MongoDB documents in JSON, JavaScript or even TypeScript files. Use

Paweł Kosiec 494 Dec 29, 2022
A Weather API project inspired by The Ultimate API Challenge / Weather API.

Weather API Project A Weather API project inspired by The Ultimate API Challenge / Weather API. Tech Stack: React.js Tailwind Axios Inspiration The Pr

Franziska 1 Dec 29, 2021
Icon Ultimate Media Viewer

Ultimate Media Viewer View everything. Supported Images Audio Videos Documents Models PNG MP4 MD GLB JPG WEBM PDF GIF M3U8 SVG 3GP WEBP ICO Download R

null 1 May 23, 2022
Ultimate Script to complete PostgreSQL-to-PostgreSQL Migration right after AWS DMS task done

Ultimate Script to complete PostgreSQL-to-PostgreSQL Migration right after AWS DMS task done

방신우 22 Dec 23, 2022