Introduction to Common Tags
The common-tags library in JavaScript is a collection of template literal tags designed to help you with powerful string manipulation functionalities. It can greatly simplify how you manage and manipulate strings in your JavaScript applications.
Setting up Common Tags
First, install the library via npm:
npm install common-tags
Important API examples
1. stripIndents
Removes leading indents from multi-line strings:
const { stripIndents } = require('common-tags');
const message = stripIndents`
Line 1
Line 2
Line 3
`; console.log(message); // Output: // Line 1 // Line 2 // Line 3
2. oneLine
Joins multiple lines into a single line string:
const { oneLine } = require('common-tags');
const message = oneLine`
This is a text
that spans multiple lines.
`; console.log(message); // Output: This is a text that spans multiple lines.
3. html
Handles HTML content and ensures proper escaping:
const { html } = require('common-tags');
const content = html`
This is a span
`; console.log(content); // Output: This is a span
4. codeBlock
Formats multi-line strings as code blocks:
const { codeBlock } = require('common-tags');
const code = codeBlock`
function add(a, b) {
return a + b;
}
`; console.log(code); // Output: // function add(a, b) { // return a + b; // }
5. safeHtml
Prevents XSS attacks by escaping HTML:
const { safeHtml } = require('common-tags');
const userInput = '';
const safeContent = safeHtml`
${userInput}
`; console.log(safeContent); // Output: <img src=x onerror=alert(1)>
Example Application
Here’s a simple example of how you might use the common-tags library in a web application:
const { stripIndents, oneLine, html } = require('common-tags'); const express = require('express'); const app = express(); const port = 3000;
app.get('/', (req, res) => {
const message = stripIndents`
Welcome to the Common Tags Demo!
This is an example of using Common Tags in an application.
`;
const oneLineMessage = oneLine`This message will be on one line.`;
const htmlMessage = html`${message}
${oneLineMessage}
`;
res.send(htmlMessage);
});
app.listen(port, () => {
console.log(oneLine`Server is running on port ${port}`);
});
In this example, we use stripIndents
, oneLine
, and html
to format and render strings properly in an Express.js application.
Happy coding with common-tags!
Hash: 543fc80b74321f7aa24430238f5678d2f449dc172322b2158932e53d7d9433f5