Reputation: 1043
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'
Upvotes: 6
Views: 14120
Reputation: 6511
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:
/##([^@]*(?:@[^@]+)*)@@/
Upvotes: 8
Reputation: 785058
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@@"]
filter(Boolean)
is needed to remove empty result from arrayUpvotes: 4
Reputation: 19764
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.
Upvotes: 4