使用regex从SVG字符串中提取viewBox属性值

时间:2018-01-19 20:54:03

标签: javascript regex svg

我有一个快速的字符串:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 18"><title>A</title><path d="M0,18V4A3.83,3.83,0,0,1,1.19,1.18,3.85,3.85,0,0,1,4,0H8a3.81,3.81,0,0,1,2.8,1.19A3.85,3.85,0,0,1,12,4V18H8V10H4v8ZM4,8H8V4A2,2,0,0,0,6,2a1.92,1.92,0,0,0-1.4.59A1.92,1.92,0,0,0,4,4Z"/></svg>

我想从视图框中检索值:

"0 0 12 18"

到目前为止我所拥有的:

/"\d\s\d\s\d\d\s\d\d"/

正如您所看到的,这并不能保证提取的值将是viewBox,而且它不包括值不是单个数字时的情况,如下所示:123 32 1239 33

2 个答案:

答案 0 :(得分:3)

您可以使用https://developer.mozilla.org/en-US/docs/Web/API/DOMParser,因为在XML / HTML上使用RegExp是不明智的

const myString = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 18"><title>A</title><path d="M0,18V4A3.83,3.83,0,0,1,1.19,1.18,3.85,3.85,0,0,1,4,0H8a3.81,3.81,0,0,1,2.8,1.19A3.85,3.85,0,0,1,12,4V18H8V10H4v8ZM4,8H8V4A2,2,0,0,0,6,2a1.92,1.92,0,0,0-1.4.59A1.92,1.92,0,0,0,4,4Z"/></svg>`;

const parser = new DOMParser();
const doc = parser.parseFromString(myString, "text/html");

console.log( doc.querySelector("svg").getAttribute("viewBox") ); // "0 0 12 18"

为什么不使用RegExp进行解析?可以说明这个简单的事实是DOM非常宽松,属性(即:像data-*)是不限制它的内容(只考虑ie:data-cont="<b data-cont='<b'></b>")等等......想象你应该写的不可持续的正则表达式噩梦。而你永远做不到。

正则表达式 ...对于“我知道我的字符串,伙计!”时刻:

const myString = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 18"><title>A</title><path d="M0,18V4A3.83,3.83,0,0,1,1.19,1.18,3.85,3.85,0,0,1,4,0H8a3.81,3.81,0,0,1,2.8,1.19A3.85,3.85,0,0,1,12,4V18H8V10H4v8ZM4,8H8V4A2,2,0,0,0,6,2a1.92,1.92,0,0,0-1.4.59A1.92,1.92,0,0,0,4,4Z"/></svg>`;

const viewBox = (/viewBox="([^"]+)"/.exec(myString)||'')[1] ;
console.log( viewBox )  // "0 0 12 18" or undefined (if not found)

答案 1 :(得分:1)

当然,您可以使用正则表达式分析短而简单的XML/HTML/SVG序列。在你的情况下,这可能是

viewBox="([^"]+)"

请参阅a demo on regex101.com以及以下代码段:

var svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 18"><title>A</title><path d="M0,18V4A3.83,3.83,0,0,1,1.19,1.18,3.85,3.85,0,0,1,4,0H8a3.81,3.81,0,0,1,2.8,1.19A3.85,3.85,0,0,1,12,4V18H8V10H4v8ZM4,8H8V4A2,2,0,0,0,6,2a1.92,1.92,0,0,0-1.4.59A1.92,1.92,0,0,0,4,4Z"/></svg>'

var match = svg.match(/viewBox="([^"]+)"/)
console.log(match[1])

然而,这是不可取的......