Returning elements in array that appear after a certain word
I would like to return all elements in array that appear after a certain word
For example given the string
let testPattern = '<name>ladder</name><prx>112</prx><qty>12</qty><name>ladder</name><prx>200</prx>'
I would get the output
['ladder', 'prx: 112', 'qty: 12', 'ladder', 'prx: 200']
This is the code I have
const result = testPattern
.match(/<[a-z]+>(.*?)<\/[a-z]+>/g)
.map(val => val.replace(/<(\w+)\>(.*)\<\/\1\>/g, '$1: $2')
.substring(testPattern.indexOf('ladder'),testPattern.length)
)
This is what I get
[ 'ladder', '12', '2', 'ladder' ,'00']
Where am I going wrong
While you could do this with a regular expression, parsing the XML would make more sense.
let testPattern = '<name>ladder</name><prx>112</prx><qty>12</qty><name>ladder</name><prx>200</prx>';
const doc = new DOMParser().parseFromString(testPattern, 'text/html');
const arr = [...doc.body.children].map(
child => child.nodeName === 'NAME' ? child.textContent : `${child.nodeName.toLowerCase()}: ${child.textContent}`
);
console.log(arr);
It's not actually HTML, but it still works.