1

I have SVG string and I need to extract its two attributes: width and height.

I can't use some XML parser since I am using this with Titanium Studio framework so I don't have DOM anywhere.

SVG's looks like this:

<svg xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink" version="1.1" width="768" height="1005" space="preserve">
    LOT OF DATA HERE... <></> etc
</svg>

I started with something like this:

var width = svgString.match( /^<svg.\width.=.(.*)$>/gm );

It's 4 AM and my brain is just not working. If someone could help it would be great! Thx.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
vale4674
  • 4,161
  • 13
  • 47
  • 72

4 Answers4

4

Assuming jmar777's code works, I would use a different, more conservative, regex, which allows for optional spaces, optional quotes and confirms that values are from svg tag itself (and not from some other tag if absent in svg tag). This might or might not make difference in your case, depending on where you get those svgs and how they are formed.

var width = svgString.match(/^<svg[^>]*width\s*=\s*\"?(\d+)\"?[^>]*>/)[1];
var height = svgString.match(/^<svg[^>]*height\s*=\s*\"?(\d+)\"?[^>]*>/)[1];
Eugene Ryabtsev
  • 2,232
  • 1
  • 23
  • 37
  • Thx, I used yours solution. I'll just modify it a little bit to search `\"` or `\'` if some SVG comes with single quote. Oh and I removed `^` from the beginning since I saw that some SVG's have doctype tag at first. – vale4674 May 17 '12 at 16:35
3
var width = svgString.match(/^<svg.*?width="(\d+)/)[1];
var height = svgString.match(/^<svg.*?height="(\d+)/)[1];
jmar777
  • 38,796
  • 11
  • 66
  • 64
  • Tnx. I used Eugene's solution which takes care od white spaces also. Yours was a good starting point so I'll up vote your answer – vale4674 May 17 '12 at 16:36
0

Be sure to make optional parts optional. (See: the dots in between the 'width' and the = sign in your regex)

var width = svgString.match( /^<svg.*width\s*=\s*\"(\d*)\"$>/gm );

(given that \s matches all whitespace and \d matches all numbers)

Riking
  • 2,389
  • 1
  • 24
  • 36
0

Here is a solution that worked in all cases i tested.

const width = parseInt(svg.substring(svg.indexOf("width")).split('=')[1].match(/^\d+|\d+\b|\d+(?=\w)/g)[0]);
const height = parseInt(svg.substring(svg.indexOf("height")).split('=')[1].match(/^\d+|\d+\b|\d+(?=\w)/g)[0]);
zaheer
  • 320
  • 5
  • 7