Categories
JavaScript Answers

How to remove all classes that begin with a certain string with JavaScript?

Spread the love

Sometimes, we want to remove all classes that begin with a certain string with JavaScript.

In this article, we’ll look at how to remove all classes that begin with a certain string with JavaScript.

How to remove all classes that begin with a certain string with JavaScript?

To remove all classes that begin with a certain string with JavaScript, we use the string startsWith method.

For instance, we write

const prefix = "prefix";
const classes = el.className.split(" ").filter((c) => {
  return !c.startsWith(prefix);
});
el.className = classes.join(" ").trim();

to call el.className.split to split the className string by the spaces into an array of substrings.

Then we call filter with a callback that filters out all entries that starts with prefix.

Next, we call join to join all the class name strings in the classes array back into a string separated by spaces.

Then we call trim to remove start and ending whitespaces.

Conclusions

To remove all classes that begin with a certain string with JavaScript, we use the string startsWith method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *