Home > Mobile >  Filter script tags into array
Filter script tags into array

Time:12-02

I have an example markup:

<p><span style="color: blue;">Yes this one now</span></p>
<p><br></p>
<p>The main configuration value is this</p>
<p><br></p>
<p>!</p>
<p>enable</p>
<p>configure terminal</p>
<p>server name <span style="color: red;">Server Name</span></p>
<p>enable secret <span style="color: red;">Server Pass</span></p>
<p>no ip domain-lookup</p>
<p>ip domain name <span style="color: red;">region</span>.google.com</p>
<p>!</p>
<p><br></p>

I want to write a Javascript to filter all the span tag data into 2 different arrays. One for when color is red and the other one when color is blue. But I am an unable to do that can someone help me out with this? I am trying wiring the JS code but my solution fails.

CodePudding user response:

You can simply use regex along with match() to get elements

const html = `<p><span style="color: blue;">Yes this one now</span></p>
<p><br></p>
<p>The main configuration value is this</p>
<p><br></p>
<p>!</p>
<p>enable</p>
<p>configure terminal</p>
<p>server name <span style="color: red;">Server Name</span></p>
<p>enable secret <span style="color: red;">Server Pass</span></p>
<p>no ip domain-lookup</p>
<p>ip domain name <span style="color: red;">region</span>.google.com</p>
<p>!</p>
<p><br></p>`

const blueArray = html.match(/(?<=<span style="color: blue;">)(.*?)(?=<\/span>)/g)

console.log(blueArray)

const redArray = html.match(/(?<=<span style="color: red;">)(.*?)(?=<\/span>)/g)

console.log(redArray)

  • Related