Categories
JavaScript Answers

How to remove line breaks from start and end of string with JavaScript?

Spread the love

Sometimes, we want to remove line breaks from start and end of string with JavaScript.

In this article, we’ll look at how to remove line breaks from start and end of string with JavaScript.

How to remove line breaks from start and end of string with JavaScript?

To remove line breaks from start and end of string with JavaScript, we can use the string replace method.

For instance, we write

const newwStr = str.replace(/^\s+|\s+$/g, "");

to call replace to remove line breaks from the start and end of the string by replacing them with empty strings.

^\s+ matches the line break at the start of the string.

\s+$ matches the line break at the end of the string.

Conclusion

To remove line breaks from start and end of 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 *