0

I am converting SVG to PNG and I need to remove the angularjs attributes in my SVG.

<rect fill="#F9B24F" ry="5" rx="5" ng-attr-y="{{node.rectY}}" ng-attr-x="{{node.rectX}}" 
  ng-attr-height="{{chart.height}}" ng-attr-width="{{chart.width}}" y="10" x="20"    
height="80" width="160">

I need ouput as

<rect fill="#F9B24F" ry="5" rx="5"  y="10" x="20"    
height="80" width="160">

I am trying to replace using String Replace method in javascript.I have tried the following in console,but it's not working

"ng-repeat='{{dddddsd}}' dfjdzjfhjk".replace(/ng-*\s/g," "); 
saiki4116
  • 323
  • 1
  • 4
  • 14
  • 2
    Don't you have to make the replacement in the source instead of at run time? – nhahtdh Oct 28 '14 at 15:48
  • I am using AngularJS ng-repeat for making a flow chart by repeating a set of SVG elements. If I remove them at source, I wont be able generate SVG dynamically based on AJAX response. – saiki4116 Oct 29 '14 at 07:44

2 Answers2

1

If you can rely on the Angular attributes always being in the form ng-xyz="...", you can do it like this:

str = str.replace(/\bng-[^\s]+="[^"]*"/g, '');

If some are in single quotes, you can follow up with a second replace:

str = str.replace(/\bng-[^\s]+='[^']*'/g, '');

Obviously that's a big "if," but it's the kind of "if" that you have to have if you want to manipulate SGML-like markup with regular expressions, which fundamentally you can't really do.

Example:

var str = '<rect fill="#F9B24F" ry="5" rx="5" ng-attr-y="{{node.rectY}}" ng-attr-x="{{node.rectX}}" ng-attr-height="{{chart.height}}" ng-attr-width="{{chart.width}}" y="10" x="20"    height="80" width="160">';
display("Before: " + str);
str = str.replace(/\bng-[^\s]+="[^"]*"/g, '');
display("After: " + str);

function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = String(msg).replace(/&/g, "&amp;").replace(/</g, "&lt;");
    document.body.appendChild(p);
}
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

don't use regex to parse DOM. (detailed answers on why here: RegEx match open tags except XHTML self-contained tags)

Just walk the DOM and strip any attributes you don't want.

var svg = $('#mySvg').clone(); //see http://api.jquery.com/clone/
var allNodes = svg.find('*');

allNodes.each( function(i,node) {
    //Here you can extract any attribute starting with ng- but not all angular directives
    //start with ng-*
    node.removeAttribute('ng-repeat');
} );
Community
  • 1
  • 1
BiAiB
  • 12,932
  • 10
  • 43
  • 63
  • Thanks..If I remove the attributes, I wont be be able to generate next Flow Chart dynamically as data bindings will be lost. Inkscape does not have issue with ng-attr and ng-repeat, but canvg library has. I will remember your solution, it will be definitely useful for me. – saiki4116 Oct 29 '14 at 07:54
  • You can proceed the attribute removal on a cloned version of your svg element – BiAiB Oct 29 '14 at 10:29