Categories
JavaScript Answers

How to split a string at the first / and surrounding part of it in a span with JavaScript?

Spread the love

Sometimes, we want to split a string at the first / and surrounding part of it in a span with JavaScript.

In this article, we’ll look at how to split a string at the first / and surrounding part of it in a span with JavaScript.

How to split a string at the first / and surrounding part of it in a span with JavaScript?

To split a string at the first / and surrounding part of it in a span with JavaScript, we can use the string replace method.

For instance, we write

date.innerHTML = date.innerHTML.replace(/^(..)\//, "<span>$1</span></br>");

to call date.innerHTML.replace with a regex that matches any content before a slash and replace the content with a span element that wraps around the content and add a br element after the span.

Then we assign the returned string back to date.innerHTML to update the content.

Conclusion

To split a string at the first / and surrounding part of it in a span 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 *