Saravanan S Saravanan S - 3 months ago 9
Javascript Question

javascript - split string by specifying starting and ending characters

I have a string

(100*##G. Mobile Dashboard||Android App ( Practo.com )||# of new installs@@-##G. Mobile Dashboard||Android App ( Practo.com )||# of uninstalls@@


I want to split the string in such a way that it returns the following result (i.e it matches all characters that starts with
##
and ends with
@@
and splits the string with matched characters)

["(100*", "G. Mobile Dashboard||Android App ( Practo.com )||# of new installs", '-', 'G. Mobile Dashboard||Android App ( Practo.com )||# of uninstalls'

Answer

Use String.prototype.split() passing a regex.

var str = "(100*##G. Mobile Dashboard||Android App ( Practo.com )||# of new installs@@-##G. Mobile Dashboard||Android App ( Practo.com )||# of uninstalls@@";

var re = /##(.*?)@@/;

var result = str.split(re);
console.log(result);

When you use Capturing parentheses in the regex, the captured text is also returned in the array.

Note that this will have an ending "" entry, because your string ends with @@. If you don't want that, just remove it.


  • If you always assume a well-formed string, the following regex yields the same result:

    /##|@@/
    

    *Commented by T.J. Crowder

  • If you expect newlines in between ## and @@, change the expression to:

    /##([\s\S]*?)@@/
    
  • If you need it to perform better, specially failing faster with longer strings:

    /##([^@]*(?:@[^@]+)*)@@/
    

    *Benchmark

Comments