• 5 String Manipulation Libraries for JavaScript
  • By Mahdhi Rezvi
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: IAMSHENSH
  • Proofread by: Gesj-Yean, CoolRice

5 large JavaScript string manipulation library

Working with strings can be a tedious task because there are many different cases. For example, something as simple as converting a string to a hump format might require a few lines of code.

function camelize(str) {
  return str.replace(/ (? :^\w|[A-Z]|\b\w|\s+)/g.function(match, index) {
    if (+match === 0) return ""; If (/\s+/.test(match))
    return index === 0 ? match.toLowerCase() : match.toUpperCase();
  });
}
Copy the code

The code above is the most liked answer on StackOverflow. But that doesn’t work with strings like –Foo– bAr.

That’s where the string handling library comes in. These libraries will make string manipulation easy and take care of all the cases where you simply need to call a method.

Let’s take a look at some JavaScript string manipulation libraries.

1. String.js

String.js, or S for short, is a lightweight (compressed to under 5KB) JavaScript library that provides additional string methods for browsers or Node.js.

The installation

npm i string
Copy the code

Interesting method

  • Between (left, right) – ExtractionleftrightBetween strings.

This gets the element between two HTML tags.

var S = require('string');
S('<a>This is a link</a>').between('<a>'.'</a>').s
// 'This is a link'
Copy the code
  • Camelize () – Remove all underscores or hyphens and convert to camel – back format.

This approach solves the problem mentioned at the beginning of this article.

var S = require('string');
S('---Foo---bAr---').camelize().s;
//'fooBar'
Copy the code
  • Humanize () – Converts input to a humanized form.

Implementing this method from scratch would certainly require many lines of code.

var S = require('string');
S(' capitalize dash-CamelCase_underscore trim ').humanize().s
//'Capitalize dash camel case underscore trim'
Copy the code
  • StripPunctuation () – Removes all symbols of the target string.

If you implement this method from scratch, you will most likely miss a symbol.

var S = require('string');
S('My, st[ring] *full* of %punct)').stripPunctuation().s;
//My string full of punct
Copy the code

Check out more methods here.

2. Voca

Voca is a JavaScript library that processes strings. Voca provides useful ways to comfortably manipulate strings: case conversion, trim, fill, Slugify, Latinize, format, truncate, escape, and more. Its modular design allows you to load the entire library or load only one method to build a minimal application. The library is well tested, well documented, and provides long-term support.

The installation

npm i voca
Copy the code

Interesting method

  • Camel Case(String data)

Converts string data to hump format.

var v = require('voca');
v.camelCase('foo Bar');
// => 'fooBar'

v.camelCase('FooBar');
// => 'fooBar'

v.camelCase('---Foo---bAr---');
// => 'fooBar'
Copy the code
  • Latinise(String data)

Data is latinized by removing metaphone characters.

var v = require('voca');
v.latinise('cafe\u0301'); / / / 'cafe'
// => 'cafe'

v.latinise('produce aout decembre');
// => 'aout decembre'

v.latinise('seem а seem п р е seem р а с е н э т о т м и р');
// => 'kak prekrasen etot mir'
Copy the code
  • isAlphaDigit(String data)

Check if data contains only Alphanumeric characters.

var v = require('voca');
v.isAlphaDigit('year2020');
// => true

v.isAlphaDigit('1448');
// => true

v.isAlphaDigit('40-20');
// => false
Copy the code
  • CountWords(String data)

Count the number of words in data.

var v = require('voca');
v.countWords('gravity can cross dimensions');
/ / = > 4

v.countWords('GravityCanCrossDimensions');
/ / = > 4

v.countWords('Gravity - can cross dimensions! ');
/ / = > 4
Copy the code
  • EscapeRegExp(String data)

Escape regular expression special characters in data — [] / {} () * +? .\ ^ $.

var v = require('voca');
v.escapeRegExp('(hours)[minutes]{seconds}');
// => '\(hours\)\[minutes\]\{seconds\}'
Copy the code

You can find more information here.

3. Anchorme.js

This is a lightweight and fast Javascript library that helps us detect links, urls, and email addresses in text and turn them into clickable HTML anchor links.

  • High sensitivity, low false positives.
  • Verify web addresses and email addresses against the complete IANA list.
  • Verify the port number (if any).
  • Verify eight-bit IP numbers (if any).
  • Applies to addresses in non-Latin letters.

The installation

npm i anchorme
Copy the code

usage

import anchorme from "anchorme";
/ / or
//var anchorme = require("anchorme").default;

const input = "some text with a link.com";
const resultA = anchorme(input);
//some text with a <a href="http://link.com">link.com</a>
Copy the code

You can pass in additional parameters to further customize the functionality.

4. Underscore String

Underscore. String is a JavaScript string manipulation extension library that you can use with or without Underscore. Underscore. String is a JavaScript library that lets you comfortably manipulate strings, inspired by prototype.js, right.js, and Underscore.

Underscore. String provides some useful methods: capitalize, clear, include, count, escape HTML, unescape HTML, insert, concatenate, header check, tail check, caption, trim, truncate, and more.

The installation

npm install underscore.string
Copy the code

Interesting method

  • NumberFormat (number) – Formats numbers

Format a number as a string with a decimal point separated in sequence.

var _ = require("underscore.string");

_.numberFormat(1000.3) = >"1000000"

_.numberFormat(123456789.123.5.'. '.', '); = >"123456789123"
Copy the code
  • Levenshtein (string1,string2) – Evaluates levenshtein between two strings.

Learn more about Levenshtein’s distance algorithm here.

var _ = require("underscore.string");

_.levenshtein('kitten'.'kittah'); = >2
Copy the code
  • Chop (string, step) – Splits a string into chunks.
var _ = require("underscore.string");

_.chop('whitespace'.3); = > ['whi'.'tes'.'pac'.'e']
Copy the code

Learn more about Underscore.String here.

5. Stringz

The highlight of the library is its support for Unicode (Unicode, universal, single). If you run the following code, the output is 2.

"🤔".length
/ / - > 2
Copy the code

This is because string.length () returns the number of bytes of the String, not the number of characters. In fact, characters between 010000 — 03FFFF and 040000 — 10FFFF require four bytes (32 bits) each, but that doesn’t change the answer: some characters require more than two bytes to represent, so a character requires more than one byte.

Read more about JavaScript Unicode issues here.

The installation

npm install stringz
Copy the code

Interesting method

  • limit(string, limit, padString, padPosition)

Limits the length of a string.

const stringz = require('stringz');

/ / cut short:
stringz.limit('Life’s like a box of chocolates.'.20);
// "Life's like a box of"

/ / fill:
stringz.limit('Everybody loves emojis! '.26.'💩');
// "Everybody loves emojis! 💩 💩 💩"
stringz.limit('What are you looking at? '.30.'+'.'left');
// "++++++What are you looking at?"

/ / support Unicode:
stringz.limit('🤔 🤔 🤔'.2);
/ / "🤔 🤔"
stringz.limit('👍 🏽 👍 🏽'.4.'👍 🏽');
/ / "👍 🏽 👍 🏽 👍 🏽 👍 🏽"
Copy the code
  • toArray(string)

Convert strings to arrays

const stringz = require('stringz');

stringz.toArray('abc');
// ['a','b','c']

/ / support Unicode:
stringz.toArray('👍 🏽 🍆 🌮');
/ / / '👍 🏽', '🍆', '🌮]
Copy the code

Visit Stringz’s Github here to learn more


If you have any suggestions or comments, let me know in the comments.

Stringjs Voca Stringz Underscore String Anchorme

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.