Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

81
Views
Extract values from html tag and replace values with HTML tag text

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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' }
]
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!