Home >Web Front-end >JS Tutorial >How Can I Split a String in JavaScript and Keep the Delimiter?

How Can I Split a String in JavaScript and Keep the Delimiter?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 11:08:06828browse

How Can I Split a String in JavaScript and Keep the Delimiter?

Splitting Strings in JavaScript While Preserving Delimiters

When attempting to split a string using a delimiter in JavaScript using the split() method, it's common to lose the delimiter in the resulting array. To address this, consider the following solutions:

For instance, given the string:

var string = "aaaaaa<br /><br />bbbb<br /><br />cccc"

We want to split this string using the delimiter
followed by a special character. Using the expression /
&#?[a-zA-Z0-9] ;/g may not preserve the delimiter.

To maintain the delimiter, consider using the following variations:

  • Capturing the Delimiter:

    string.split(/(<br \/>)/g);

    This expression uses parentheses to capture the delimiter, ensuring it remains in the resulting array.

  • Positive Lookahead:

    string.split(/(?=</g);

    This expression splits the string at each position where the delimiter is to the right, but doesn't capture the delimiter itself.

  • Negative Lookahead:

    string.split(/(?!</g);

    This expression splits the string at each position where the delimiter is not to the right, maintaining the delimiter in the resulting array.

Alternatively, for a more customized approach, you can use the following expression:

string.split(/(.*?<br \/>)/g);

This expression captures everything up to and including the delimiter, removing only the special character.

Note that certain expressions may only split single characters. In such cases, alternatives like the following can be used:

// Keep slashes after directories
var str = 'Animation/rawr/javascript.js';
var tokens = str.match(/[^\/]+\/?|\//g);

The above is the detailed content of How Can I Split a String in JavaScript and Keep the Delimiter?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn