Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
like image 581
Saravanan S Avatar asked Aug 07 '16 10:08

Saravanan S


3 Answers

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

like image 179
Mariano Avatar answered Oct 05 '22 13:10

Mariano


You can first split by ##, then split each of the results by @@, and flatten the resulting array, like the following.

s.split('##').map(el => el.split('@@')).reduce((acc, curr) => acc.concat(curr))

Note that the last element of the resulting array will be empty string if you original string ends with @@, so you might need to remove it, depending on your use-case.

like image 20
Lazar Ljubenović Avatar answered Oct 05 '22 11:10

Lazar Ljubenović


You can use:

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

var arr = s.split(/(##.*?@@)/).filter(Boolean)

//=> ["(100*", "##G. Mobile Dashboard||Android App ( Practo.com )||# of new installs@@", "-", "##G. Mobile Dashboard||Android App ( Practo.com )||# of uninstalls@@"]
  • Use a capturing group to get split text in resulting array
  • filter(Boolean) is needed to remove empty result from array
like image 40
anubhava Avatar answered Oct 05 '22 12:10

anubhava