Handle case conversion, delete letter symbols, Unicode processing, URL processing, etc.

Using strings can be a tedious task because there are many different use cases. For example, a simple task such as converting a string to hump case might take a few lines of code to achieve the final goal.

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

The code snippet above is the most voted answer in StackOverflow. But that doesn’t solve the case where the string is —-Foo—-bAr—–.

This is where string processing libraries come to the rescue, as they make it easy to implement complex string operations and consider all possible use cases for a given problem. This helps because you only need to call one method to get an effective solution.

Let’s look at some JavaScript string processing libraries.

1. String.js

String.js, or S for short, is a lightweight JavaScript library (compressed to less than 5KB) used by browsers or node.js that provides additional string methods.

The installation

npm i string
Copy the code

A noteworthy approach

Between (left, right) — Extracts the string between left and right strings. You can use this method when trying to get an element between two tags in HTML.

var S = require('string');
S('<a>This is a link</a>').between('<a>'.'</a>').s 
// 'This is a link'
Copy the code

Camelize () — Removes any underscores or dashes and converts the string to camelhumped uppercase letters. This feature can be used to solve the problem mentioned at the beginning of this article.

var S = require('string');
S('---Foo---bAr---').camelize().s; 
//'fooBar'
Copy the code

Humanize () – Converts the input to a humanized form. Implementing this feature from scratch certainly requires quite a bit 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 punctuation from a given string. If you implement this feature from scratch, you will most likely miss the punctuation.

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

You can check out more methods here.

2. Voca

Voca is a JavaScript library for processing strings. The Voca library provides useful functions to make it easy to manipulate strings: changing case, modifying, filling, elasticizing, Latinizing, sprintfy, truncating, escaping, and more. The modular design allows entire libraries or individual functions to be loaded to minimize application build. The library has been thoroughly tested, documented and supported for a long time.

The installation

npm i voca
Copy the code

A noteworthy approach

Camel Case(String Data) – Converts 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) — Latinise data by removing diacritical marks.

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

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

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

IsAlphaDigit (String Data) — Checks if the data contains only alphanumeric and numeric characters. (Alphanumeric)

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

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

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

CountWords(String data) — Counts the number of words in the 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 the data -[] / {} () * +? . $| \ ^.

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

You can check out more information here.

3. Anchorme.js

This is a tiny fast Javascript library that helps detect links/urls/emails in text and convert them into clickable HTML links.

  • It has high sensitivity and the lowest false alarm rate.
  • It verifies the URL and email against the full IANA list.
  • Verify the port number (if any).
  • Verify the IP octet byte number, if it exists.
  • Applies to non-Latin letter urls.

The installation

npm i anchorme
Copy the code

use

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 extensions to further customize the functionality.

You can check out more information here.

4. Underscore.string

Underscore. String is a string manipulation extension of JavaScript that can be used with or without Underscore. Underscore. String is a JavaScript library for handling strings comfortably, and it is an extension of prototype.js, right.js, and Underscore inspired by Underscore.

Underscore. String provides you with several useful functions: capitalize, clear, include, count, escapeHTML, unescapeHTML, Insert, splice, startsWith, endsWith, captioning, trim, truncate, and more.

The installation

npm install underscore.string
Copy the code

A noteworthy approach

NumberFormat (number) — Formats numbers. Formats numbers into a string with decimal points and sequentially delimited.

var _ = require("underscore.string");
_.numberFormat(1000.3) = >"1000000"
_.numberFormat(123456789.123.5.'. '.', '); = >"123456789123"
Copy the code

Chop (string, step) — To cut a given string into small pieces.

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

You can check out more information here.

5. Stringz

The main highlight of the library is its Support for Unicode. If you run the following code, the output is 2.

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

This is because string.length () returns the number of code units in the String, not the number of characters.

You can read more about JavaScript Unicode issues here.

The installation

npm install stringz
Copy the code

A noteworthy approach

Limit (String, limit, padString, padPosition) — Limits the string to the given width.

const stringz = require('stringz');
// Truncate:
stringz.limit('Life’s like a box of chocolates.'.20); 
// "Life's like a box of"

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

// Unicode Aware:
stringz.limit('🤔 🤔 🤔'.2); 
/ / "🤔 🤔"
stringz.limit('👍 🏽 👍 🏽'.4.'👍 🏽'); 
/ / "👍 🏽 👍 🏽 👍 🏽 👍 🏽"
Copy the code

ToArray (String) — Converts a string to an array.

const stringz = require('stringz');
stringz.toArray('abc');
// ['a','b','c']
//Unicode aware
stringz.toArray('👍 🏽 🍆 🌮');
/ / / '👍 🏽', '🍆', '🌮]
Copy the code

To learn more about Stringz, visit it on Github here.


Source: blog.bitsrc. IO, by Mahdhi Rezvi, translated by: Front Foreign Language collection

This article is first published in the public number “front-end Foreign language selection”, after attention to the private message reply: gift package, send a network high-quality video course online disk data, can save you a lot of money!