0

Here I have text something like this:

  1. const string = 'Welcome;;to::';
  2. const string ='Welcome;;';

I want to split this string with ;; and ::;

Expected result: ['Welcome', ';;', 'to', '::']

There will be chance that number of pattern will be increased. So, is this possible ?

Note: There is no space between words.

Dhaval Parmar
  • 241
  • 1
  • 3
  • 13
  • 1
    Split by non-word characters and use a capturing group so it's included in the resulting array – CertainPerformance May 30 '22 at 13:56
  • See also: https://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript – omid May 30 '22 at 13:56
  • result = string.split(";;").join(" ;; ").split("::").join(" ::").split(" "); – Dave Pritlove May 30 '22 at 14:02
  • 3
    or result = string.replace(";;", " ;; ").replace("::", " ::").split(" "); You basically need to insert spaces around the delimiters and perform a final split to remove them. – Dave Pritlove May 30 '22 at 14:04
  • `let arr = 'Welcome;;to::'.match(/\w+|\W+/g)` – Jamie Dixon May 30 '22 at 14:20
  • @Dave Pritlove If it's dynamic then how to split then ? Like if in this case there is two pattern (;;, ::) now if it has three then how to handle dynamically ? – Dhaval Parmar May 30 '22 at 15:15
  • 2
    if there's always no spaces, you would simply pass each delimeter to `replace("xx", " xx ")` to insert the spaces before the final split on " ". If the string ends with a delimiter, as your example is, you'll have to only insert the space behind it (or remove the resulting element at the end of the array afterwards). – Dave Pritlove May 30 '22 at 15:34

0 Answers0