I would like to extract values between tags that match a pattern. I want to then return a string where the text preceding the extracted value matches the text within the tag.
Here is an example to make this clearer. Assuming this is the string:
let testPattern = '<name>ladder</name><prx>112</prx><qty>12</qty>'
I would expect this as the outcome
name- ladder prx- 112 qty- 12
This is what I tried
var result = testPattern.match(/<[a-z]+>(.*?)<\/[a-z]+>/g).map(function(val){
return val.replace(/<\/?[a-z]+>/g,'$1, $2')
})
This is my outcome
[ '$1, $2ladder$1, $2', '$1, $2112$1, $2', '$1, $212$1, $2' ]
What am I doing wrong?
Your issue is your inner regex, this should do the trick.
const result = testPattern
.match(/<[a-z]+>(.*?)<\/[a-z]+>/g)
.map(val => val.replace(/<(\w+)\>(.*)\<\/\1\>/g,'$1 $2'))
Although maybe dividing it into an object could be a better option? Especially if you want to access the tag and the tag's contents separately. Perhaps something like:
const testPattern = '<name>ladder</name><prx>112</prx><qty>12</qty>'
const regex = /<(\w+)\>(.*)\<\/\1\>/g
const result = testPattern
.match(/<[a-z]+>(.*?)<\/[a-z]+>/g)
.map((val) => ({
tag: val.replace(regex, '$1'),
val: val.replace(regex, '$2') }))
Resulting in :
[
{ tag: 'name', val: 'ladder' },
{ tag: 'prx', val: '112' },
{ tag: 'qty', val: '12' }
]