JavaScript

JavaScript: Split string and keep the separators

Advertisements

String.prototype.split() is a valuable method to split strings based on a delimiter. There often comes a scenario when we want to split a string and keep the separators in the result. The same JavaScript method provides a way to do so.

Before we get into that, for people who are unfamiliar with split(), here’s a quick refresher.

Split()

The function can be called on a string with two parameters. The first is the separator on which we want to split the input string. And the second is the limit which is an optional parameter and specifies the number of times that the separator should be matched.

The separator can be a string or a regex.

const inputString = 'The quick brown fox jumps over the lazy dog.';
console.log(inputString.split(" "));
//  ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.']
JavaScript

Using regex for the separator:

console.log(inputString.split(/ /));
// ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.']
JavaScript

Splitting and keeping the separators

As the MDN docs for Split() state:

When found, separator is removed from the string, and the substrings are returned in an array.

But there is a workaround for regular expressions. Using positive lookaheads, we can assert that the regular expression exists, but not actually match it. In simpler words, if parenthesis, that is ( and ), are used in the separator, matched results are included in the array.

const inputString = 'Hello 1 word. Sentence number 2.'
const splits = inputString.split(/(\d)/)

console.log(splits)
// [ "Hello ", "1", " word. Sentence number ", "2", "." ]
JavaScript

Note: \d matches the character class for digits between 0 and 9.

Thus we can use lookarounds to separate strings and keep the separators too! This opens up easier ways to solve some string-parsing problems.

Saransh Kataria

Born in Delhi, India, Saransh Kataria is the brain behind Wisdom Geek. Currently, Saransh is a software developer at a reputed firm in Austin, and he likes playing with new technologies to explore different possibilities. He holds an engineering degree in Computer Science. He also shares his passion for sharing knowledge as the community lead at Facebook Developer Circle Delhi, NCR which is a developer community in Delhi, India.

Share
Published by
Saransh Kataria
Tags: javascript

Recent Posts

How To Get The Hash of A File In Node.js

While working on a project, I wanted to do an integrity check of a file…

20 hours ago

Native popover API in HTML

Popovers have been a problem that was typically solved by using a third-party solution. But…

1 week ago

Node.js 20.6 adds built-in support for .env files

Node.js 20.6 added built-in support for the .env file. This is an excellent addition to the platform…

2 weeks ago

Object destructuring in TypeScript

Object destructuring is a powerful ES 6 feature that can help developers write cleaner code.…

4 weeks ago

Improve git clone performance in a CI pipeline

Have you felt particularly annoyed by the time it takes to clone a large repository,…

1 month ago

Fix: Hydration failed because the initial UI does not match what was rendered on the server

Within a React or Next.js app, if you encounter the error "Hydration failed because the…

1 month ago
Advertisements