Sara Ree
Sara Ree

Reputation: 3543

Split the string by any of given delimiters

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!

Upvotes: 4

Views: 119

Answers (5)

jonatjano
jonatjano

Reputation: 3738

Here's a solution without regex if you want to avoid them

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

function multisplit(input, ...splits) {
  input = [input]
  while (splits.length) {
    let splitter = splits.shift()
    input = input.flatMap(sub => sub.split(splitter))
  }
  return input.map(el => el.trim())
}

console.log(multisplit(a, "*", "||"))

Upvotes: 2

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15550

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)

Upvotes: 5

Yousaf
Yousaf

Reputation: 29354

You could use String.prototype.match() which will return you an array of matches found in the string for a given regex.

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

console.log(a.match(/\w+/g));

Upvotes: 3

Majed Badawi
Majed Badawi

Reputation: 28434

const a = "they *have* a* car* sold. ||They* eat* the * good * stuff";
let arr = a.split(/\*|\|\|/);
console.log(...arr);

Upvotes: 2

Beso Kakulia
Beso Kakulia

Reputation: 602

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

a = a.replace(/[^a-zA-Z ]/g, "")
a = a.split(' ')

Upvotes: 2

Related Questions