我想使用dangerouslySetInnerHTML显示SVG。
<div dangerouslySetInnerHTML={{__html:props.SVG_Thumbnail__c}} />
但是,我得到的SVG数据是一个转义的HTML字符串。
我虽然这是Frontend的一个常见案例。但是,我做了谷歌搜索没有任何内置方法可以完美地处理所有转义字符。
逃避方法不起作用。
处理此字符串的常用方法是什么?
每次都写下替换方法吗?
var escaped = str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
<svg width="100%" height="100%&q%" fill="#ffffff"/><text x="5%" y="50%" font-family="Lato" font-size="8px" alignment-baseline="middle" fill="#37444e">Primary Content</text></svg><svg x="10%" y="64%" width="90%" height="26%"><rect x="0" y="0" width="100%" height="100%" fill="#ffffff"/><text x="5%" y="50%" font-family="Lato" font-size="8px" alignment-baseline="middle" fill="#37444e">Secondary Content</text></svg></svg>
答案 0 :(得分:2)
您可以做的一件事是将转义值分配给HTML元素的innerHTML
属性,然后使用textContent
属性将其以非转义形式恢复。
function unescapeHtml(value) {
var div = document.createElement('div');
div.innerHTML = value;
return div.textContent;
}
var escapedValue = '<svg width="100%" height="100%&q%" fill="#ffffff"/><text x="5%" y="50%" font-family="Lato" font-size="8px" alignment-baseline="middle" fill="#37444e">Primary Content</text></svg><svg x="10%" y="64%" width="90%" height="26%"><rect x="0" y="0" width="100%" height="100%" fill="#ffffff"/><text x="5%" y="50%" font-family="Lato" font-size="8px" alignment-baseline="middle" fill="#37444e">Secondary Content</text></svg></svg>';
var unescapedValue = unescapeHtml(escapedValue);
console.log(unescapedValue);