I have some XML content that looks like this:
<Artificial name="Artifical name">
<Machine>
<MachineEnvironment uri="environment" />
</Machine>
<Mobile>taken phone, test
when r1
100m SUV
then
FireFly is High
end
when r2
Order of the Phonenix
then
Magic is High
end
</Mobile>
</Artificial>
My goal is to create a function that takes a line (string) and content (string) as input and returns the content of the closest tag that the provided line belongs to.
For example, if I provide the line FireFly is High
, the expected output should be as follows since it is the closest tag that contains the provided line:
<Mobile>taken phone, test
when r1
100m SUV
then
FireFly is High
end
when r2
Order of the Phonenix
then
Magic is High
end
</Mobile>
Below is the code snippet I have so far:
getLineContent(line: string, content: string) {
const trimmedLine = line.trim()
const isSelfClosingTag = /\/\s*>$/.test(trimmedLine)
const isPlainTextLine = !/<|>/.test(trimmedLine)
const regex = new RegExp(`(${trimmedLine}[^>]*>)([\\s\\S]*?)</(${trimmedLine.split(' ')[0].substr(1)}>)`)
const isClosingTag = /^<\/\w+>$/.test(trimmedLine)
const match = content.match(regex)
if (!isClosingTag) {
if (isSelfClosingTag) {
return trimmedLine
}
if (match && match[2]) {
return match[1] + match[2] + match[3]
}
if (isPlainTextLine) {
const regex = new RegExp(`(<[^>]*>)([\\s\\S]*?${trimmedLine.split(' ')[0].substr(1)}[\\s\\S]*?</[a-zA-Z]+>)`)
const match = content.match(regex)
console.log('isPlainTextLine', match)
if (match && match[1] && match[2]) {
return match[2]
}
}
return trimmedLine
}
}
The code works almost perfectly but there are still some issues, particularly in this part:
if (isPlainTextLine) {
const regex = new RegExp(`(<[^>]*>)([\\s\\S]*?${trimmedLine.split(' ')[0].substr(1)}[\\s\\S]*?</[a-zA-Z]+>)`)
const match = content.match(regex)
console.log('isPlainTextLine', match)
if (match && match[1] && match[2]) {
return match[2]
}
}
For instance, providing FireFly is High
results in:
<Machine>
<MachineEnvironment uri="environment" />
</Machine>
<Mobile>taken phone, test
when r1
100m SUV
then
FireFly is High
end
when r2
Order of the Phonenix
then
Magic is High
end
</Mobile>
I'm not very familiar with regex. Any assistance would be greatly appreciated.