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
Release: 2024-12-09 11:08:06
Original
833 people have browsed it

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"
Copy after login

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);
    Copy after login

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

  • Positive Lookahead:

    string.split(/(?=</g);
    Copy after login

    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);
    Copy after login

    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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template