Tari Ibaba

Tari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.

How to Remove a Class From Multiple Elements With JavaScript

To remove a class from multiple elements in JavaScript:

  1. Get a list of all the elements with a method like document.querySelectorAll(selector).
  2. Iterate over the list with forEach().
  3. For each element, call classList.remove(class) to remove the class from each element.

i.e.:

const elements = document.querySelectorAll('.class');

elements.forEach((element) => {
  element.classList.remove('class');
});

For example:

HTML

<p class="big bold text">Coding</p>
<p class="big bold text">Beauty</p>
<p class="big bold text">Dev</p>

<button id="remove">Remove class</button>

JavaScript

const removeBtn = document.getElementById('remove');

removeBtn.addEventListener('click', () => {
  const elements = document.querySelectorAll('.text');

  elements.forEach((element) => {
    element.classList.remove('big');
  });
});

CSS

.bold {
  font-weight: bold;
}

.big {
  font-size: 1.2em;
}

This will be the HTML after the button is clicked:

<p class="bold text">Coding</p>
<p class="bold text">Beauty</p>
<p class="bold text">Dev</p>

<button id="remove">Remove class</button>
The big class is removed from the texts when the button is clicked.
The big class is removed from the texts when the button is clicked.

We use the document.querySelectorAll() method to select all DOM elements from which we want to remove the class.

We iterate over the elements in the list object with the forEach() method. This forEach() method works similarly to Array forEach().

document.getElementsByClassName() method

We can use the document.getElementsByClassName() method in place of the document.querySelectorAll() method when the selector is a class selector. For getElementsByClassName(), we pass the class name without the . (dot), and we use Array.from() to convert the result to an array before the iteration with forEach().


const elements = Array.from(document.getElementsByClassName('text'));
elements.forEach((element) => {
  element.classList.remove('big');
});

classList.remove() method

We use the classList.remove() method to remove a class from the elements. You can remove multiple classes by passing more arguments to remove().

const elements = document.querySelectorAll('.text');

elements.forEach((element) => {
  element.classList.remove('big', 'bold');
});

If any of the classes passed to remove() doesn’t exist on the element, remove() will ignore it, instead of throwing an error.

Remove class from multiple elements with different selectors

Sometimes there is no common selector between the elements that you want to remove the class from. For such a case, you can pass multiple comma-separated selectors to the querySelectorAll() method.

const elements = document.querySelectorAll('.text, #box-1, #box-2');

elements.forEach((element) => {
  element.classList.remove('bold');
});

Add class to multiple elements

Just like the classList.remove() method removes one or more classes from an element, the classList.add() method adds one or more classes to an element. This means that we can use it in the forEach() method to remove a class from multiple DOM elements:

const elements = document.querySelectorAll('.text');
elements.forEach((element) => {
  element.classList.add('italic', 'underline');
});

How to Sort an Object Array by a Boolean Property in JavaScript

To sort an array of objects by a boolean property in JavaScript, call the sort() method on the array with a callback as an argument. In the function, use the boolean property to return an expression that evaluates to a positive number, a negative number, or zero. This will sort the array in place, by the boolean property, i.e.:

const trueFirst = users.sort((a, b) => b.boolProp - a.boolProp);

const falseFirst = users.sort((a, b) => a.boolProp - b.boolProp);

For example:

const users = [
  { name: 'Kate', premium: false },
  { name: 'Bob', premium: true },
  { name: 'Jeff', premium: false },
  { name: 'Samantha', premium: true },
];

const premiumFirst = users.sort((a, b) => b.premium - a.premium);

/*
  [
    { name: 'Bob', premium: true },
    { name: 'Samantha', premium: true },
    { name: 'Kate', premium: false },
    { name: 'Jeff', premium: false }
  ]
*/

console.log(premiumFirst);

const nonPremiumFirst = users.sort((a, b) => a.premium - b.premium);

/*
  [
    { name: 'Kate', premium: false },
    { name: 'Jeff', premium: false },
    { name: 'Bob', premium: true },
    { name: 'Samantha', premium: true }
  ]
*/

console.log(nonPremiumFirst);

The Array sort() method takes a callback function as an argument. It uses the value returned from this callback to determine the order in which to sort the values. For each item pair in the array, a and b:

If the returned value is negative, a is placed before b in the sorted array.

If the value is positive, b is placed before a.

If the value is 0, the order of a and b is not changed.

const arr = [5, 3, 8, 1, 7];

// Sort in ascending order
arr.sort((a, b) => a - b);

console.log(arr); // [ 1, 3, 5, 7, 8 ]

// Sort in descending order
const desc = arr.sort((a, b) => b - a);

console.log(desc); // [ 8, 7, 5, 3, 1 ]

Because we used the subtraction operator (-) on the boolean values, they are coerced to numbers before the subtraction happens. Truthy values are coerced to 1, and falsy values 0.

console.log(true + true); // 2

console.log(true + false); // 1

console.log(false + false); // 0

After seeing how the sort() method and boolean coercion works, it’s easy to understand the way the was sorted to place the objects with a boolean property value of true above the ones with false, and vice versa.

Sort object array by boolean property without mutation

The sort() method sorts the array in place, which means it gets modified. To prevent this, we can use the spread syntax (...) to create a shallow copy of the array for the sort:

const users = [
  { name: 'Kate', premium: false },
  { name: 'Bob', premium: true },
  { name: 'Jeff', premium: false },
  { name: 'Samantha', premium: true },
];

// 👇 Clone array with spread syntax
const premiumFirst = [...users].sort((a, b) => b.premium - a.premium);

/*
  [
    { name: 'Bob', premium: true },
    { name: 'Samantha', premium: true },
    { name: 'Kate', premium: false },
    { name: 'Jeff', premium: false }
  ]
*/

console.log(premiumFirst);

/*
  Original not modified:
  [
    { name: 'Kate', premium: false },
    { name: 'Bob', premium: true },
    { name: 'Jeff', premium: false },
    { name: 'Samantha', premium: true }
  ]
*/

console.log(users);

By avoiding mutations, we can make our code more readable, predictable, and modular.

How to Convert XML to JSON in Node.js

We can use the xml-js library from NPM to easily convert XML to JSON in Node.js, i.e.:

import { xml2json } from 'xml-js';

// ...

const json = xml2json(xml);

For example:

index.js

import { xml2json } from 'xml-js';
import fs from 'fs/promises';

// Read from file
// const xml = await fs.readFile('data.xml',  { encoding: 'utf-8' });

const xml = `<name>Garage</name>
<cars>
    <color>red</color>
    <maxSpeed>120</maxSpeed>
    <age>2</age>
</cars>
<cars>
    <color>blue</color>
    <maxSpeed>100</maxSpeed>
    <age>3</age>
</cars>
<cars>
    <color>green</color>
    <maxSpeed>130</maxSpeed>
    <age>2</age>
</cars>`;

const json = xmltojson(xml, );

console.log(json);

This code will have the following JSON output:

{"declaration":{"attributes":{"version":"1.0","encoding":"UTF-8"}},"elements":[{"type":"element","name":"languages","elements":[{"type":"element","name":"language","elements":[{"type":"text","text":"\n      English\n   "}]},{"type":"element","name":"language","elements":[{"type":"text","text":"\n      French\n   "}]},{"type":"element","name":"language","elements":[{"type":"text","text":"\n      Spanish\n   "}]}]}]}

What are XML and JSON?

Let’s go through these terms in case you’re not familiar with them

XML (eXtensible Markup Language) is a markup language similar to HTML that was designed to store and transport data. Unlike HTML, XML doesn’t have any predefined tags. Instead, we define our own tags according to our requirements.

Example of XML data:

<users>
   <user>
     <name>Jack</name>
   </user>
   <user>
     <name>Samantha</name>
   </user>
</users>

JSON (JavaScript Object Notation) is a text format used to store and transport data based on JavaScript object syntax and is commonly used to build RESTful APIs.

Example of JSON data:

{
  "users": [
    {
      "name": "Jack"
    },
    {
      "name": "Samantha"
    }
  ]
}

You saw more examples of XML and JSON data in the previous section.

Install xml-js

Before using xml-js, we need to install it in our Node.js project. We can do this with the NPM CLI.

npm i xml-js

# Yarn
yarn add xml-js

After installation, we’ll be able to import it into a JavaScript module, like this:

import { xml2json } from 'xml-js';

// CommonJS
const { xml2json } = require('xml-js');

We use import destructuring to access the xml2json() method directly from the library.

The xml2json() function

The xml2json() function has two parameters. The first is the XML string to convert to JSON, and the second is an optional object.

const json = xml2json(xml, { spaces: 2, compact: true });

Customize conversion of XML to JSON in Node.js

We use this object to specify various options for customizing the conversion process.

In our example, we don’t pass an object, so the default options are used. We can pass an object with a spaces option to properly format and indent the resulting JSON.

import { xml2json } from 'xml-js';

const xml = `<?xml version="1.0" encoding="UTF-8"?>
<languages>
   <language>
      English
   </language>
   <language>
      French
   </language>
   <language>
      Spanish
   </language>
</languages>`;

// 👇 Set "spaces" option
const json = xml2json(xml, { spaces: 2 });

console.log(json);

Here’s the new output:

{
  "declaration": {
    "attributes": {
      "version": "1.0",
      "encoding": "UTF-8"
    }
  },
  "elements": [
    {
      "type": "element",
      "name": "languages",
      "elements": [
        {
          "type": "element",
          "name": "language",
          "elements": [
            {
              "type": "text",
              "text": "\n      English\n   "
            }
          ]
        },
        {
          "type": "element",
          "name": "language",
          "elements": [
            {
              "type": "text",
              "text": "\n      French\n   "
            }
          ]
        },
        {
          "type": "element",
          "name": "language",
          "elements": [
            {
              "type": "text",
              "text": "\n      Spanish\n   "
            }
          ]
        }
      ]
    }
  ]
}

The compact property to determine whether the resulting JSON should be detailed or compact. It is false by default.

import { xml2json } from 'xml-js';

const xml = `<?xml version="1.0" encoding="UTF-8"?>
<languages>
   <language>
      English
   </language>
   <language>
      French
   </language>
   <language>
      Spanish
   </language>
</languages>`;

// 👇 Set "compact" option
const json = xml2json(xml, { spaces: 2, compact: true });

console.log(json);

Now the resulting JSON will have a significantly smaller size than before:

{
  "_declaration": {
    "_attributes": {
      "version": "1.0",
      "encoding": "UTF-8"
    }
  },
  "languages": {
    "language": [
      {
        "_text": "\n      English\n   "
      },
      {
        "_text": "\n      French\n   "
      },
      {
        "_text": "\n      Spanish\n   "
      }
    ]
  }
}

NEW: *Built-In* Syntax Highlighting on Medium

If you frequently read or write coding articles on Medium you’ll know that it hasn’t had any syntax highlighting support for years now, despite programming being one of the most common topics on the platform. Software writers have had to resort to third-party tools to produce beautiful code highlighting that enhances readability.

Luckily, all that should change soon, as recently the Medium team finally added built-in syntax highlighting support to the code block for major programming languages.

The Medium code block now has syntax highlighting support.
The Medium code block now has syntax highlighting support.

As you can see in the demo, the code block can now automatically detect the code’s language and highlight it.

Manual syntax highlighting

Auto-detection doesn’t always work correctly though, especially for small code snippets, possibly due to the syntax similarities between multiple languages. Notice in the demo how the language detected changed during typing, from R to C++ to Go before arriving at JavaScript.

For tiny code snippets, auto-detection will likely fail:

Auto-detection fails to correctly detect the language.
Bash?

In such a case you can select the correct language from the drop-down list:

Manually setting the language for syntax highlighting.
Manually setting the language for syntax highlighting.

Remove syntax highlighting

If the code is of a language not listed or it doesn’t require highlighting, you can select None and remove the highlighting.

Removing syntax highlighting with the "None" option.
Removing syntax highlighting with the None option.

Note that syntax highlighting isn’t applied to articles published before the feature arrived, probably because it would produce incorrect results in them if auto-detection failed.

So now we no longer need GitHub Gists or Carbon for this. Syntax highlighting on Medium is now easier than ever before.

How to Add Months to a Date in JavaScript

1. Date getMonth() and setMonth() methods

To add months to a Date in JavaScript:

  1. Call the getMonth() to get the number of months.
  2. Add the new months.
  3. Pass the sum to the setMonth() method.

For example:

function addMonths(date, months) {
  date.setMonth(date.getMonth() + months);

  return date;
}

// May 17, 2022
const date = new Date('2022-05-17T00:00:00.000Z');

const newDate = addMonths(date, 4);

// September 17, 2022
console.log(newDate); // 2022-09-17T00:00:00.000Z

Our addMonths() takes a Date object and the number of months to add as arguments. It returns the same Date object with the newly added months.

The Date getMonth() returns a zero-based number that represents the month of a particular date.

The Date setMonth() method sets the months of a date to a specified zero-based number.

Note: “Zero-based” here means that 0 is January, 1 is February, 2 is March, etc.

If the months added would increase the year of the Date, setMonth() will automatically update the information in the Date object to reflect this.

// November 12, 2022
const date = new Date('2022-11-12T00:00:00.000Z');

date.setMonth(date.getMonth() + 3);

// February 12, 2023
console.log(date); // 2023-02-12T00:00:00.000Z

Here we added 3 months to a date in November 2022. This makes setMonth() automatically update the year to 2023.

Avoid side effects

The setMonth() method mutates the Date object it is called on. This introduces a side effect in our addMonths() function. To avoid modifying the passed Date and create a pure function, make a copy of the Date and call setMonth() on this copy, instead of the original.

function addMonths(date, months) {
  // 👇 Make copy with "Date()" constructor
  const dateCopy = new Date(date);

  dateCopy.setMonth(dateCopy.getMonth() + months);

  return dateCopy;
}

// August 16, 2022
const date = new Date('2022-08-16T00:00:00.000Z');

const newDate = addMonths(date, 3);

// November 16, 2022
console.log(newDate); // 2022-11-16T00:00:00.000Z

// 👇 Original not modified
console.log(date); // 2022-08-16T00:00:00.000Z

Tip: Functions that don’t modify external state (i.e., pure functions) tend to be more predictable and easier to reason about, as they always give the same output for a particular input. This makes it a good practice to limit the number of side effects in your code.

2. date-fns addMonths() function

Alternatively, we can use the addMonths() function from the date-fns library to quickly add months to a Date. It works like our pure addMonths() function.

import { addMonths } from 'date-fns';

// July 14, 2022
const date = new Date('2022-07-14T00:00:00.000Z');

const newDate = addMonths(date, 1);

// August 14, 2022
console.log(newDate); // 2022-08-14T00:00:00.000Z

// Original not modified
console.log(date); // 2022-07-14T00:00:00.000Z

How to Convert CSV to an Array in JavaScript

You can the csvtojson library to quickly convert a CSV file or string to an array of objects in JavaScript:

index.js

import csvToJson from 'csvtojson';

const csvFilePath = 'data.csv';


const array = await csvToJson().fromFile(csvFilePath);

console.log(array);

For a data.csv file like this:

data.csv

color,maxSpeed,age
"red",120,2
"blue",100,3
"green",130,2

This will be the resulting array:

Output

[
  { color: 'red', maxSpeed: '120', age: '2' },
  { color: 'blue', maxSpeed: '100', age: '3' },
  { color: 'green', maxSpeed: '130', age: '2' }
]

Install csvtojson

Before using csvtojson, you’ll need to install it in our project. You can do this with the NPM or Yarn CLI.

npm i csvtojson

# Yarn
yarn add csvtojson

After installation, you’ll be able to import it into a JavaScript module, like this:

import csvToJson from 'csvtojson';

// CommonJS
const csvToJson = require('csvtojson');

Convert CSV file to array with fromFile()

We call the default export function of the csvtojson module to create the object that will convert the CSV to the array. This object has a bunch of methods, each related in some way to the conversion of CSV to a JavaScript object, and fromFile() is one of them.

It accepts the name of the CSV file to convert, and returns a Promise, as the conversion is an asynchronous process. The Promise will resolve with the resulting JSON string.

Convert CSV string to array with fromString()

To convert from a CSV data string directly, instead of a file, you can use the also asynchronous fromString() method of the converter object instead:

index.js

import csvToJson from 'csvtojson';

const csv = `"First Name","Last Name","Age"
"Russell","Castillo",23
"Christy","Harper",35
"Eleanor","Mark",26`;

const array = await csvToJson().fromString(csv);

console.log(array);

Output

[
  { 'First Name': 'Russell', 'Last Name': 'Castillo', Age: '23' },
  { 'First Name': 'Christy', 'Last Name': 'Harper', Age: '35' },
  { 'First Name': 'Eleanor', 'Last Name': 'Mark', Age: '26' }
]

Customize conversion of CSV to array

The default export function of csvtojson accepts an object used to specify options to customize the conversion process.

One such option is header, an array used to specify the headers in the CSV data.

index.js

import csvToJson from 'csvtojson';

const csv = `"First Name","Last Name","Age"
"Russell","Castillo",23
"Christy","Harper",35
"Eleanor","Mark",26`;

const array = await csvToJson({
  headers: ['firstName', 'lastName', 'age'],
}).fromString(csv);

console.log(array);

Output

[
  { firstName: 'Russell', lastName: 'Castillo', age: '23' },
  { firstName: 'Christy', lastName: 'Harper', age: '35' },
  { firstName: 'Eleanor', lastName: 'Mark', age: '26' }
]

Another is delimeter, used to indicate the character that separates the columns:

import csvToJson from 'csvtojson';

const csv = `"First Name"|"Last Name"|"Age"
"Russell"|"Castillo"|23
"Christy"|"Harper"|35
"Eleanor"|"Mark"|26`;

const array = await csvToJson({
  headers: ['firstName', 'lastName', 'age'],
  delimiter: '|',
}).fromString(csv);

Output

[
  { firstName: 'Russell', lastName: 'Castillo', age: '23' },
  { firstName: 'Christy', lastName: 'Harper', age: '35' },
  { firstName: 'Eleanor', lastName: 'Mark', age: '26' }
]

We also have ignoreColumns, an option that instructs the converter to ignore certain columns, using a regular expression.

import csvToJson from 'csvtojson';

const csv = `"First Name"|"Last Name"|"Age"
"Russell"|"Castillo"|23
"Christy"|"Harper"|35
"Eleanor"|"Mark"|26`;

const array = await csvToJson({
  headers: ['firstName', 'lastName', 'age'],
  delimiter: '|',
  ignoreColumns: /lastName/,
}).fromString(csv);

console.log(array);

Output

[
  { firstName: 'Russell', age: '23' },
  { firstName: 'Christy', age: '35' },
  { firstName: 'Eleanor', age: '26' }
]

Convert CSV to array of rows

By setting the output option to 'csv', we can produce a list of arrays, where each array represents a row, containing the value of all columns of that row.

For example:

index.js

import csvToJson from 'csvtojson';

const csv = `color,maxSpeed,age
"red",120,2
"blue",100,3
"green",130,2`;

const array = await csvToJson({
  output: 'csv',
}).fromString(csv);

console.log(array);

Output

[
  [ 'red', '120', '2' ],
  [ 'blue', '100', '3' ],
  [ 'green', '130', '2' ]
]

Native conversion of CSV to array

It’s also possible to convert CSV to a JavaScript array without using any third-party libraries.

index.js

function csvToArray(csv) {
  // \n or \r\n depending on the EOL sequence
  const lines = csv.split('\n');
  const delimeter = ',';

  const result = [];

  const headers = lines[0].split(delimeter);

  for (const line of lines) {
    const obj = {};
    const row = line.split(delimeter);

    for (let i = 0; i < headers.length; i++) {
      const header = headers[i];
      obj[header] = row[i];
    }

    result.push(obj);
  }

  // Prettify output
  return JSON.stringify(result, null, 2);
}

const csv = `color,maxSpeed,age
"red",120,2
"blue",100,3
"green",130,2`;

const array = csvToArray(csv);

console.log(array);

Output

[
  {
    "color": "color",
    "maxSpeed": "maxSpeed",
    "age": "age"
  },
  {
    "color": "\"red\"",
    "maxSpeed": "120",
    "age": "2"
  },
  {
    "color": "\"blue\"",
    "maxSpeed": "100",
    "age": "3"
  },
  {
    "color": "\"green\"",
    "maxSpeed": "130",
    "age": "2"
  }
]

You can modify the code above to allow for varying and more complex CSV data.

How to Convert CSV to JSON in JavaScript

You can use the csvtojson library to quickly convert CSV to JSON in JavaScript:

index.js

index.js
import csvToJson from 'csvtojson'; const csvFilePath = 'data.csv'; const json = await csvToJson().fromFile(csvFilePath); const jsonString = JSON.stringify(json, null, 2) console.log(jsonString);

For a data.csv file like this:

data.csv
color,maxSpeed,age "red",120,2 "blue",100,3 "green",130,2

This will be the resulting JSON:

JSON
[ { "color": "red", "maxSpeed": "120", "age": "2" }, { "color": "blue", "maxSpeed": "100", "age": "3" }, { "color": "green", "maxSpeed": "130", "age": "2" } ]

We use csvtojson to convert the CSV into a JSON object, and use the JSON.stringify() method to convert the object into a well-formatted JSON string.

Install csvtojson

Before using csvtojson, you’ll need to install it in our project. You can do this with the NPM or Yarn CLI.

Shell
npm i csvtojson # Yarn yarn add csvtojson

After installation, you’ll be able to import it into a JavaScript module, like this:

JavaScript
import csvToJson from 'csvtojson'; // CommonJS const csvToJson = require('csvtojson');

Convert CSV file to JSON with fromFile()

We call the default export function of the csvtojson module to create the object that will convert the CSV. This object has a bunch of methods, each related in some way to the conversion of CSV to JSON, and fromFile() is one of them.

It accepts the name of the CSV file to convert, and returns a Promise, as the conversion is an asynchronous process. The Promise will resolve with the resulting JSON string.

Convert CSV string to JSON with fromString()

To convert from a CSV data string directly, instead of a file, you can use the also asynchronous fromString() method of the converter object instead:

index.js
import csvToJson from 'csvtojson'; const csv = `"First Name","Last Name","Age" "Russell","Castillo",23 "Christy","Harper",35 "Eleanor","Mark",26`; const json = await csvToJson().fromString(csv); const jsonString = JSON.stringify(json, null, 2); console.log(jsonString); 
JSON
[ { "First Name": "Russell", "Last Name": "Castillo", "Age": "23" }, { "First Name": "Christy", "Last Name": "Harper", "Age": "35" }, { "First Name": "Eleanor", "Last Name": "Mark", "Age": "26" } ]

Customize conversion of CSV to JSON

The default export function of csvtojson accepts an object used to specify options to customize the conversion process.

One such option is header, an array used to specify the headers in the CSV data.

index.js
import csvToJson from 'csvtojson'; const csv = `"First Name","Last Name","Age" "Russell","Castillo",23 "Christy","Harper",35 "Eleanor","Mark",26`; const json = await csvToJson({ headers: ['firstName', 'lastName', 'age'], }).fromString(csv); console.log(json);
JSON
[ { "firstName": "Russell", "lastName": "Castillo", "age": "23" }, { "firstName": "Christy", "lastName": "Harper", "age": "35" }, { "firstName": "Eleanor", "lastName": "Mark", "age": "26" } ]

Another is delimeter, used to indicate the character that separates the columns:

index.js
import csvToJson from 'csvtojson'; const csv = `"First Name"|"Last Name"|"Age" "Russell"|"Castillo"|23 "Christy"|"Harper"|35 "Eleanor"|"Mark"|26`; const json = await csvToJson({ headers: ['firstName', 'lastName', 'age'], delimiter: '|', }).fromString(csv); const jsonString = JSON.stringify(json, null, 2); console.log(jsonString);
JSON
[ { "firstName": "Russell", "lastName": "Castillo", "age": "23" }, { "firstName": "Christy", "lastName": "Harper", "age": "35" }, { "firstName": "Eleanor", "lastName": "Mark", "age": "26" } ]

We also have ignoreColumns, an option that instructs the converter to ignore certain columns, using a regular expression.

index.js
import csvToJson from 'csvtojson'; const csv = `"First Name"|"Last Name"|"Age" "Russell"|"Castillo"|23 "Christy"|"Harper"|35 "Eleanor"|"Mark"|26`; const json = await csvToJson({ headers: ['firstName', 'lastName', 'age'], delimiter: '|', ignoreColumns: /lastName/, }).fromString(csv); const jsonString = JSON.stringify(json, null, 2); console.log(jsonString);
JSON
[ { "firstName": "Russell", "age": "23" }, { "firstName": "Christy", "age": "35" }, { "firstName": "Eleanor", "age": "26" } ]

Convert CSV to JSON array of rows

By setting the output option to 'csv', we can produce a list of arrays, where each array represents a row, containing the value of all columns of that row.

For example:

index.js
import csvToJson from 'csvtojson'; const csv = `color,maxSpeed,age "red",120,2 "blue",100,3 "green",130,2`; const json = await csvToJson({ output: 'csv', }).fromString(csv); const jsonString = JSON.stringify(json, null, 2); console.log(jsonString);
JSON
[ [ "red", "120", "2" ], [ "blue", "100", "3" ], [ "green", "130", "2" ] ]

Native conversion of CSV to JSON

It’s also possible to convert CSV to JSON without using any third-party libraries.

index.js
function csvToJson(csv) { // \n or \r\n depending on the EOL sequence const lines = csv.split('\n'); const delimeter = ','; const result = []; const headers = lines[0].split(delimeter); for (const line of lines) { const obj = {}; const row = line.split(delimeter); for (let i = 0; i < headers.length; i++) { const header = headers[i]; obj[header] = row[i]; } result.push(obj); } // Prettify output return result; } const csv = `color,maxSpeed,age red,120,2 blue,100,3 green,130,2`; const json = csvToJson(csv); const jsonString = JSON.stringify(json, null, 2); console.log(jsonString);

You can modify the code above to allow for varying and more complex CSV data.

Output:

JSON
[ { "color": "color", "maxSpeed": "maxSpeed", "age": "age" }, { "color": "red", "maxSpeed": "120", "age": "2" }, { "color": "blue", "maxSpeed": "100", "age": "3" }, { "color": "green", "maxSpeed": "130", "age": "2" } ]

How to Open a Link in a New Tab Programmatically in React

To open a link in a new tab programmatically in React, call the window.open() method with the link as an argument, e.g., window.open('https://codingbeautydev.com'). The open() method will open the link in a new browser tab.

In the following example, we programmatically open the link in a new tab at the end of a countdown:

App.js

import { useRef, useEffect, useState } from 'react';

export default function App() {
  const [timeLeft, setTimeLeft] = useState(3);
  const interval = useRef();

  useEffect(() => {
    interval.current = setInterval(() => {
      // Decrease "timeLeft" by 1 every second
      setTimeLeft((prev) => prev - 1);
    }, 1000);

    return () => clearInterval(interval.current);
  }, []);

  useEffect(() => {
    // Open the link in a new tab when the countdown ends
    if (timeLeft === 0) {
      clearInterval(interval.current);

      // 👇 Open link in new tab programmatically
      window.open('https://codingbeautydev.com', '_blank', 'noreferrer');
    }
  }, [timeLeft]);

  return (
    <div>
      The link will open in <b>{timeLeft}</b> second(s)
    </div>
  );
}
The link is opened in a new tab when the countdown ends.
The link is opened in a new tab when the countdown ends.

We use the open() method of the window object to programmatically open a link in a new tab. This method has three optional parameters:

  1. url: The URL of the page to open in a new tab.
  2. target: like the target attribute of the <a> element, this parameter’s value specifies where to open the linked document, i.e., the browsing context. It accepts all the values the target attribute of the <a> element accepts.
  3. windowFeatures: A comma-separated list of feature options for the window. noreferrer is one of these options.

Passing _blank to the target parameter makes the link get opened in a new tab.

Being able to open a link in a new tab programmatically means that we can use a button in place of an anchor link to open a URL on click. We’d just set an onClick event listener on the button element and call the window.open() method in the listener.

For example:

App.js

export default function App() {
  const openInNewTab = (url) => {
    window.open(url, '_blank', 'noreferrer');
  };

  return (
    <div>
      <p>Visit codingbeautydev.com in a new tab</p>

      <button
        role="link"
        onClick={() => openInNewTab('https://codingbeautydev.com')}
      >
        Visit
      </button>
    </div>
  );
}
Clicking the button opens the link in a new tab.
Clicking the button opens the link in a new tab.

How to Quickly Open a Link in a New Tab in React

To open a link in a new tab in React, create an anchor (<a>) element and set its target attribute to _blank, e.g., <a href="https://codingbeautydev.com" target="_blank">Link</a>. The _blank value specifies that the link should be opened in a new tab.

For example:

App.js

export default function App() {
  return (
    <div id="app">
      <a href="https://codingbeautydev.com" target="_blank" rel="noreferrer">
        Coding Beauty
      </a>

      <br />
      <br />

      <a
        href="https://codingbeautydev.com/blog"
        target="_blank"
        rel="noreferrer"
      >
        Coding Beauty Blog
      </a>
    </div>
  );
}

The target property of the anchor element specifies where to open the linked document. By default target has a value of _self, which makes the linked page open in the same frame or tab where it was clicked. To make the page open in a new tab, we set target to _blank.

We also set the rel prop to noreferrer for security purposes. It prevents the opened page from gaining any information about the page that it was opened from.

Clicking the link opens the URL in a new tab.
Clicking the link opens it in a new tab.

We can use the window.open() method to programmatically open a link in a new tab in React, e.g., window.open(url, '_blank', 'noreferrer').

For example:

App.js

import { useRef, useEffect, useState } from 'react';

export default function App() {
  const [timeLeft, setTimeLeft] = useState(3);
  const interval = useRef();

  useEffect(() => {
    interval.current = setInterval(() => {
      // Decrease "timeLeft" by 1 every second
      setTimeLeft((prev) => prev - 1);
    }, 1000);

    return () => clearInterval(interval.current);
  }, []);

  useEffect(() => {
    // Open the link in a new tab when the countdown ends
    if (timeLeft === 0) {
      clearInterval(interval.current);

      // 👇 Open link in new tab programmatically
      window.open('https://codingbeautydev.com', '_blank', 'noreferrer');
    }
  }, [timeLeft]);

  return (
    <div>
      The link will open in <b>{timeLeft}</b> second(s)
    </div>
  );
}
The link is opened in a new tab when the countdown ends.
The link is opened in a new tab when the countdown ends.

We use the open() method of the window object to programmatically open a link in a new tab. This method has three optional parameters:

  1. url: The URL of the page to open in a new tab.
  2. target: like the target attribute of the <a> element, this parameter’s value specifies where to open the linked document, i.e., the browsing context. It accepts all the values the target attribute of the <a> element accepts.
  3. windowFeatures: A comma-separated list of feature options for the window. noreferrer is one of these options.

Passing _blank to the target parameter makes the link get opened in a new tab.

Being able to open a link in a new tab programmatically means that we can use a button in place of an anchor link to open a URL on click. We’ll just set an onClick event listener on the button element and call the window.open() method in the listener.

For example:

App.js

export default function App() {
  const openInNewTab = (url) => {
    window.open(url, '_blank', 'noreferrer');
  };

  return (
    <div>
      <p>Visit codingbeautydev.com in a new tab</p>

      <button
        role="link"
        onClick={() => openInNewTab('https://codingbeautydev.com')}
      >
        Visit
      </button>
    </div>
  );
}
Clicking the button opens the link in a new tab.
Clicking the button opens the link in a new tab.

How to Check if a String Contains Uppercase Letters in JavaScript

To check if a string contains uppercase letters in JavaScript, call the test() method on this regular expression /[A-Z]/, i.e., /A-Z/.test(str). test() will return true if the string contains any uppercase letters. Otherwise, it will return false.

For example:

function containsUppercase(str) {
  return /[A-Z]/.test(str);
}

console.log(containsUppercase('javascript')); // false
console.log(containsUppercase('PHP')); // true
console.log(containsUppercase('Coding')); // true

The RegExp test() method searches a string for matches with a specified regular expression and returns true if any are found. Otherwise, it returns false.

The forward slashes (/ /) indicate the start and end of the regular expression.

The square brackets ([ ]) match any one of a given set of characters. The A-Z pattern specifies that these characters be all the letters from A to Z in uppercase. So the complete regular expression matches any capital letter in the string.

Check if string contains only uppercase letters

To check if a string contains only uppercase letters, we’ll need to use a slightly different regex: /^[A-Z]+$/.

function containsUppercase(str) {
  return /^[A-Z]+$/.test(str);
}

console.log(containsUppercase('javascript')); // false
console.log(containsUppercase('PHP')); // true
console.log(containsUppercase('Coding')); // false

Let’s look into the differences in this new regex:

The ^ character specifies that the pattern must be at the start of the string. Conversely, the $ character indicates that the pattern must be at the end.

The + character matches one or more consecutive occurrences of the preceding pattern in the string.

So matches for the regex will only be found in a string that contains a group of consecutive uppercase letters from the start to the end of the string – a string with only uppercase letters.

Check out this cheat sheet from the MDN docs for a comprehensive guide to regular expression syntax.

String match() method

An alternative to RegExp test() is the String match() method. Instead of calling test() on the regex, we call match() on the string with the regex as an argument.

function containsUppercase(str) {
  return Boolean(str.match(/[A-Z]/));
}

console.log(containsUppercase('javascript')); // false
console.log(containsUppercase('PHP')); // true
console.log(containsUppercase('Coding')); // true

The String match() method returns an array of all the matches of a regular expression in a string. If there are no matches, it returns null.

const str1 = 'javascript';
const str2 = 'Beauty';

console.log(str1?.match(/[A-Z]/)); // null
console.log(str2?.match(/[A-Z]/)); // [ 'B', ... ] (single-item array)

We pass the result of match() to the Boolean() constructor to convert it to a Boolean. Boolean converts truthy values to true, and falsy values to false.

In JavaScript, there are six falsy values: undefinednullNaN0'' (empty string), and false. Every other value is truthy.

console.log(Boolean(undefined)); // false
console.log(Boolean(['letters'])); // true
console.log(Boolean(null)); // false
console.log(Boolean(5)); // true

We used the optional chaining operator (?.) on the string variable. If the variable is undefined or null, this operator will prevent the method call and return undefined instead of throwing an error.

const str = null;

console.log(str?.match(/[A-Z]/)); // undefined