0

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(/(^<$>)/));
7
  • 3
    Regex is NOT a good tool to parse XML / HTML Commented Feb 3, 2020 at 19:16
  • hah, @Nicolas you beat me to the share ^^ Commented Feb 3, 2020 at 19:16
  • @Scrimothy this type of question is so frequent, i have it ready for copy and paste. Commented Feb 3, 2020 at 19:17
  • You can create a regex for very very simple cases but you would never be able to parse a full page. Commented Feb 3, 2020 at 19:17
  • @Nicolas you answer is Gold :D Commented Feb 3, 2020 at 19:18

2 Answers 2

1

You can do something like

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

  console.log(output);

Sign up to request clarification or add additional context in comments.

3 Comments

filter(Boolean) ?
Thanks @nickzoum
This is incorrect as your forcing just the span tag in the split
0

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

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

console.log(c);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.