Javascript regex. Need to extract value from a SVG

2019-08-02 09:40发布

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.

4条回答
冷血范
2楼-- · 2019-08-02 09:43

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)

查看更多
手持菜刀,她持情操
3楼-- · 2019-08-02 09:48

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];
查看更多
smile是对你的礼貌
4楼-- · 2019-08-02 09:59
var width = svgString.match(/^<svg.*?width="(\d+)/)[1];
var height = svgString.match(/^<svg.*?height="(\d+)/)[1];
查看更多
闹够了就滚
5楼-- · 2019-08-02 10:00

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]);
查看更多
登录 后发表回答