Categories
JavaScript Answers

How to trim specific character from a string with JavaScript?

Spread the love

Sometimes, we want to trim specific character from a string with JavaScript.

In this article, we’ll look at how to trim specific character from a string with JavaScript.

How to trim specific character from a string with JavaScript?

To trim specific character from a string with JavaScript, we can use the string replace method.

For instance, we write

const x = "|f|oo||";
const y = x.replace(/^\|+|\|+$/g, "");

to call x.replace with a regex with the characters we want to match and replace them all with empty strings.

We use the g flag to find all matches in x.

Conclusion

To trim specific character from a string with JavaScript, we can use the string replace 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 *