Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split the string by any of given delimiters

Tags:

javascript

I have this ugly sentences separated with ||.

const a = "they *have* a* car* sold. ||They* eat* the * good * stuff";

How can I split the given string by * or || signs so that we get this result:

['they', 'have','a', 'car', 'sold', 'they', 'eat', 'the ', 'good ', 'stuff'];

I don't mind spacing issues I want the split by this or that functionality.

Note: we can achieve this simply using a map but I wonder if there is a solution by regex or something!

like image 548
Sara Ree Avatar asked Dec 08 '22 10:12

Sara Ree


1 Answers

To make it more gengeral, you may

  • .split() by one or more consequent (+ quantifier) non-alphabetic characters (/[^a-z]/),
  • apply .filter(Boolean) to get rid of empty strings in resulting array (which may appear under certain circumstances)
  • use Array.prototype.map() to apply lower-casing to each word (String.prototype.toLowerCase())

const src = "they *have* a* car* sold. ||They* eat* the * good * stuff",

      result = src
        .split(/[^a-z]+/i)
        .filter(Boolean)
        .map(w => w.toLowerCase())
      
console.log(result)
like image 54
Yevgen Gorbunkov Avatar answered Dec 17 '22 20:12

Yevgen Gorbunkov