-4

I have to split a string into an array. It has to split when it finds the special substring denoted by '@ + keyword'. Example of keywords:

  • @alpha
  • @beta
  • @lolli

    Input:

    'AAHSD@alphaHDHDG@alphaSGTDHDGT@betaSDGSDFHDG@alphaASFAGF@lolliSFDSFG@alphaSGHSHSF@lolliGA'

    Desired Output

    [A,A,H,S,D, @alpha, H,D,H,D,G, @alpha, S,G,T,D,H,D,G,T, @beta, S,D,G,S,D,F,H,D,G, @alpha, A,S,F,A,G,F, @lolli, S,F,D,S,F,G, @alpha, S,G,H,S,H,S,F, @lolli, G,A]

mb925
  • 137
  • 14
  • 2
    There are [hundreds of string splitting questions](https://stackoverflow.com/search?q=%5Btypescript%5D+split+string) already, what have you tried? – CodeCaster Jan 08 '20 at 11:29
  • https://stackoverflow.com/questions/7888238/javascript-split-string-on-uppercase-characters please refer this – siddharth shah Jan 08 '20 at 11:32

2 Answers2

0

It's a good task for using regular expressions.

In your case regular expression will look like: @(alpha|beta|loli)

https://regex101.com/r/Rfx0ih/2

You can iterate over match collection and use match indexes to cut required strings.

or just use:

'AAHSD@alphaHDHDG@alphaSGTDHDGT@betaSDGSDFHDG@alphaASFAGF@lolliSFDSFG@alphaSGHSHSF@lolliGA'.split(/@(alpha|beta|lolli)/)
Alexander Trakhimenok
  • 6,019
  • 2
  • 27
  • 52
  • what if there are more then three keywords ? then you would have to add them manually. – siddharth shah Jan 08 '20 at 11:41
  • It should be OK up to few hundreds. I don't get "you would have to add them manually" - as a developer if you need to add something you do. There are different ways how you keep information and what algoritms you use but source data is source data and either harcoded or loaded from somewhere. It's up to developer to decide what works best in his/here case. – Alexander Trakhimenok Jan 08 '20 at 11:44
  • yes, it is one of the solutions but not an efficient one. Please check my answer to get more idea. It will cover all the keywords – siddharth shah Jan 08 '20 at 11:46
  • You can't judge solution without defining requirements and input data. For now you don't know for sure if in between there is low case data. And you solution is not complete as it returns "D@alpha" for example that need to be cleaned additionally. – Alexander Trakhimenok Jan 08 '20 at 11:48
  • @AlexanderTrakhimenok This sounds good to me. It's true I will need to add them manually, but for now it's okay. When I see them increase, I will take time to think to something more scalable. I will try it out and let you know. – mb925 Jan 08 '20 at 12:46
0

It is very simple You can split it from the Capital letters to get desired outcome like follows:-

'AAHSD@alphaHDHDG@alphaSGTDHDGT@betaSDGSDFHDG@alphaASFAGF@lolliSFDSFG@alphaSGHSHSF@lolliGA'.split(/(?=[A-Z])/);
siddharth shah
  • 1,139
  • 1
  • 9
  • 17