Sachihiro
Sachihiro

Reputation: 1781

Split string on matching patterns using regular expressions

I am trying to split a string by matching some patterns using regex, for instance i have <span>Hello World</span> and the result would be ["<span>", "Hello World", "</span>"]

// Tried this
console.log(arr.split(/(<*>)/));
// and this:
console.log(arr.split(/(^<$>)/));

Upvotes: 0

Views: 33

Answers (2)

varoons
varoons

Reputation: 3887

const a = `<span>Hello World</span>`; 

var c = a.split(/^(<.*>)(.*?)(<.*?>)$/g).filter(x => x);

console.log(c);

Upvotes: 0

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22885

You can do something like

  const s = `<span>Hello World</span>`; 
  const output = s.split(/(<\/?span>)/g).filter(Boolean);

  console.log(output);

Upvotes: 1

Related Questions