我有休闲字符串:
<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>
我想从 View 框中检索值:
"0 0 12 18"
我目前拥有的:
/"\d\s\d\s\d\d\s\d\d"/
如您所见,这并不能保证提取的值将是 viewBox,而且它不包括值不是个位数的情况,例如:123 32 1239 33
最佳答案
你可以使用 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-*
)不是限制性的在它的内容上(想想即: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)
关于javascript - 使用正则表达式从 SVG 字符串中提取 viewBox 属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48349400/