marcilles Stanislas
marcilles Stanislas

Reputation: 77

Get specific content in svg file with js

I need to retrieve a specific content like this "{ content }" in my svg file

So I think I need to use a regex but i don't know how to do

test.svg

<svg width="500" height="100">
    <text x="47.872" y="11.064" id="smartCar">{garage/temp} °C</text>
    <circle id="circle1" cx="20" cy="20" r="10"
            style="stroke: none; fill: #ff0000;"/>
    <text x="47.872" y="11.064" id="smartCar">{home/sensors/temp/kitchen} °C</text>
</svg>

findContent.js

    var fs = require('fs');

const fileContent = fs.readFileSync( "test.svg","UTF-8");
const lines = fileContent.split("\n");
console.log(lines);
lines.forEach((line) => {
    const topicMatch = line.match();  //need regex
            if (topicMatch) {
                console.log(topicMatch[1]) // display all content with syntax {content}
            }
})

Expected result:

Upvotes: 2

Views: 183

Answers (2)

Ryszard Czech
Ryszard Czech

Reputation: 18611

Use

const regex = /{[^{}]+}/g

const string = `<svg width="500" height="100">
    <text x="47.872" y="11.064" id="smartCar">{garage/temp} °C</text>
    <circle id="circle1" cx="20" cy="20" r="10"
            style="stroke: none; fill: #ff0000;"/>
    <text x="47.872" y="11.064" id="smartCar">{home/sensors/temp/kitchen} °C</text>
</svg>`

console.log(string.match(regex))

See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  {                        '{'
--------------------------------------------------------------------------------
  [^{}]+                   any character except: '{', '}' (1 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  }                        '}'

Upvotes: 0

Ihor Yanovchyk
Ihor Yanovchyk

Reputation: 786

Try this one:

/\{[\w\/]+\}/g

You can test it here

Upvotes: 1

Related Questions